我遇到了一点困难。基本上,我通过jQuery和AJAX将表单中的信息发送到MySQL,然后将值返回给我的应用程序。
我可以将信息添加到我的数据库中,但我似乎不知道如何检索插入的数据的ID。这是我的代码-
function submitDeliveryDetails(){
$.ajax({
url: "http://www.mydomain.co.uk/mobileapp/add_deliverydetails.php?callback=jsonp1",
data: addDeliveryData, // Variable holding said delivery information
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
$.each(data, function(index) {
alert(data[index].orderId);
});
},
error: function(){
//Do Stuff
}
})
}
这样可以很好地发送信息。我可以添加到数据库中,并使用以下内容返回ID
$orderId = mysql_insert_id();
然后我为这个值创建JSON格式,
$orderIdArray = array('orderId'=>$orderId);
echo $_GET['callback'].'('.json_encode($orderIdArray).')';
当我在FireBug中看到这个时,我可以看到ID,我需要的指导是如何处理这个ID以将其返回到我的应用程序中,因为我正在以自己的方式"未定义"做事!
谢谢Rory
p.s.我使用JSONP,因为我在一个单独的域上处理脚本。
纯文本JSON-
({"orderId":125})
这需要更改编码流,但您需要进行ajax调用,然后在ajax调用成功完成后继续成功处理程序中的执行流。
从概念上讲,它是这样的:
function submitDeliveryDetails(){
$.ajax({
url: "http://www.mydomain.co.uk/mobileapp/add_deliverydetails.php?callback=jsonp1",
data: addDeliveryData, // Variable holding said delivery information
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
$.each(data, function(index) {
alert(data[index].orderId);
});
// you can now continue on here with whatever you wanted to do
// with the the returned JSON data
// You can operate on the data here or call other functions
// (passing the data as an argument to those functions)
},
error: function(){
//Do Stuff
}
})
}
submitDeliveryDetails();
// nothing else to do here because the ajax call has not completed yet
// so the returned results from the ajax call is not available yet
您应该修改submitDeliveryDetails函数以进行成功和错误回调,然后从jQuery ajax成功和错误调用这些回调:
function submitDeliveryDetails(options){
$.ajax({
url: "http://www.mydomain.co.uk/mobileapp/add_deliverydetails.php?callback=jsonp1",
data: addDeliveryData, // Variable holding said delivery information
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
if (options && typeof(options.success) === 'function' ) options.success(data);
},
error: function(xhr, status, err){
if (options && typeof(options.error) === 'function' ) options.error(xhr, status, err);
}
});
}
然后称之为:
submitDeliveryDetails({
success: function(order) {
alert(order.orderId);
},
error: function(xhr, status, err) {
// Do Stuff
}
);