【发布时间】:2014-07-14 07:17:08
【问题描述】:
在我的混合应用程序(使用 jQM 作为框架)中,我尝试从服务器检索数据。
我尝试了 $.post 和 $.ajax 方法。
使用 $.ajax,我可以使用 "data[0].name" 访问返回数据。
使用 $.post 和完全相同的返回数据,当我尝试使用 "data[0].name" 访问数据时,我得到 "undefined" 。
我的代码有效($.ajax)并向我显示正确的数据:
$(document).on('pagebeforeshow', '#restaurantList', function() {
$.ajax({
url: "http://mydomain.com/api/restaurant/allstate/allcuisine",
type: "POST",
dataType: "json",
success: function (data) {
alert(data[0].restaurant_id);
}
});
});
我的代码不起作用($.post)并给我“未定义”:
$(document).on('pagebeforeshow', '#restaurantList', function() {
$.post("http://mydomain.com/api/restaurant/allstate/allcuisine",
function(data){
alert(data[0].restaurant_id);
});
});
这是为什么呢?我需要使用 $.post 是有原因的,但我无法访问数据。我检查了返回 JSON,两种方法都返回完全相同的数据。
请指出这两者之间的区别以及为什么我从 $.post 方法中得到 "undefined"。谢谢。
【问题讨论】:
-
$.post向$.ajax传递了不同的默认值,因此您需要完整显示您的 Ajax 代码。$.post是$.ajax({ type: "POST", url: url, data: data, success: success, dataType: dataType });的简写形式,也可以使用免费工具(如 Fiddler2)检查返回数据,因为您可能只是遇到服务器错误。 -
嗨@TrueBlueAussie,感谢您的评论。我添加了我测试过的示例代码。请指教,谢谢。
-
您检查过流量吗(使用 F12 Chrome 调试工具或安装 Fiddler2)?
-
流量是指入站数据吗?我正在使用英特尔的 XDK 开发工具。它内置了调试工具。
-
入站数据,是的。您需要查看响应是否不同(不默认为
json等)。
标签: jquery ajax jquery-mobile