【问题标题】:jQM Difference between $.post and $.ajax and I get error with $.postjQM $.post 和 $.ajax 之间的区别,我得到 $.post 错误
【发布时间】: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


【解决方案1】:

为了让 $.post 与 JSON 返回数据一起正常工作。必须指定数据类型。

根据jQM文档:

dataType 类型:字符串 服务器预期的数据类型。 默认值:智能猜测(xml、json、脚本、文本、html)。

但它的智能猜测似乎不够智能。

为此,请添加“json”,示例如下:

$(document).on('pagebeforeshow', '#restaurantList', function() {
    $.post("http://mydomain.com/api/restaurant/allstate/allcuisine",
    function(data){
        alert(data[0].restaurant_id);
    }, "json");
    });

【讨论】:

    猜你喜欢
    • 2012-09-30
    • 2011-02-20
    • 2017-03-10
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 2016-04-22
    • 1970-01-01
    相关资源
    最近更新 更多