【问题标题】:Jquery get array detailsjQuery获取数组详细信息
【发布时间】:2010-04-26 18:06:23
【问题描述】:

我无法从 Jquery ajax 调用返回响应...

(这是一个验证用户的脚本,需要返回他们的姓名和用户ID。我的理解是我可以将其编码为JSON并获取以下格式的数据。

它正在为 alert() 返回“未定义”错误

javascript

$.ajax({
 type: "POST",
 url: "myURL.php",
 data: {username: username, password: password},
 success: function(results) {
  //THIS IS WHERE THE PROBLEM IS
  alert('Hi '+results.name); //Should be "Hi Basil Fawlty"
  }
});

PHP (myURL.php)

//This comes from a SQL call that returns the following name
json_encode(array(
 'id'=>1,
 'name'=>'Basil Fawlty'
));

任何关于我哪里出错的帮助或想法将不胜感激!

谢谢。

解决方案:解决方案是添加数据类型。

【问题讨论】:

  • 您使用的是哪个版本的 jQuery?
  • 您可以在这里发布您使用 alert(results.responceText) 获得的信息吗?
  • 我使用的是 1.3 版。输出是“未定义”
  • 感谢回复,指定 dataType JSON 解决了​​这个问题。

标签: php jquery json


【解决方案1】:

你错过了dataType: "json"

$.ajax({
 type: "POST",
 url: "myURL.php",
 dataType: "json",
 data: {username: username, password: password},
 success: function(results) {
  //THIS IS WHERE THE PROBLEM IS
  alert('Hi '+results.name); //Should be "Hi Basil Fawlty"
  }
});

另一个(不那么冗长)替代方案是 jQuery.getJSON,如果您知道您正在获取 JSON。

【讨论】:

    【解决方案2】:

    如果您使用 jQuery dataType: "json"。

    从 1.4 开始,dataType 默认为:

    智能猜测(xml、json、脚本、 或 html)

    但这要求响应头包含字符串“json”。所以你要发送:

    header('Content-type: application/json');

    这种新增加的 dataType 灵活性允许处理程序响应多个返回的类型。

    如果问题仍然存在,您需要提醒整个响应 alert(results); 以查看实际返回的内容。

    这里有很多类似的答案。不知道是谁发起的,但毫无疑问是谁入侵了波兰。

    【讨论】:

    • 感谢您的回答。如果可以的话,我会为波兰的评论投两次票!
    • 我想我们都是同时作曲的。
    【解决方案3】:

    确保将 dataType 设置为 JSON,以便在成功方法中获取响应对象,如下所示:

    $.ajax({
     type: "POST",
     url: "myURL.php",
     dataType: "json",
     data: {username: username, password: password},
     success: function(results) {
      alert('Hi '+results.name);
     }
    });
    

    Details for dataType can be found here.

    或者,you can do this:

    $.getJSON( "myURL.php", {username: username, password: password}, 
      function(results) {
        alert('Hi '+results.name);
    });
    

    【讨论】:

    • 感谢 dataType 的链接和关于 getJSON 的信息。
    【解决方案4】:

    我的猜测是你期待的是 JSON,但你得到的是一个字符串。

    【讨论】:

      【解决方案5】:

      您需要像这样在请求中指定数据类型:

      $.ajax({
       type: "POST",
       url: "myURL.php",
       data: {username: username, password: password},
       dataType: "json", 
       success: function(results) {
        //THIS IS WHERE THE PROBLEM IS
        alert('Hi '+results.name); //Should be "Hi Basil Fawlty"
        }
      });
      

      或者您可以使用 php 从 php 设置内容类型

      header( "Content-Type: application/json" );
      

      【讨论】:

        猜你喜欢
        • 2011-06-06
        • 1970-01-01
        • 1970-01-01
        • 2012-06-02
        • 2020-10-08
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多