简体   繁体   English

从 Jquery JSON 获得响应

[英]Getting Response From Jquery JSON

I'm having trouble getting a response from my php jquery / json / ajax. I keep combining all these different tutorials together but I still can't seem to pull it all together since no one tutorial follow what I'm trying to do.我无法从我的 php jquery / json / ajax 获得回复。我一直将所有这些不同的教程组合在一起,但我似乎仍然无法将它们全部组合在一起,因为没有一个教程遵循我正在尝试做的事情。

Right now I'm trying to pass two arrays (since there's no easy way to pass associative arrays) to my jquery ajax function and just alert it out.现在我正在尝试将两个 arrays(因为没有简单的方法来传递关联数组)传递给我的 jquery ajax function 并提醒它。 Here's my code:这是我的代码:

PHP PHP

$names = array('john doe', 'jane doe');
$ids = array('123', '223');

$data['names'] = $names;
$data['ids'] = $ids;

echo json_encode($data);

Jquery Jquery

function getList(){
    $.ajax({  
        type: "GET", 
        url: 'test.php', 
        data: "",  
        complete: function(data){ 
            var test = jQuery.parseJSON(data);
            alert(test.names[0]);
            alert("here");
        }
    },
        "json");
}
getList();

In my html file all I'm really calling is my javascript file for debugging purposes.在我的 html 文件中,我真正调用的是用于调试目的的 javascript 文件。 I know i'm returning an object but I'm getting an error with null values in my names section, and i'm not sure why.我知道我返回的是 object,但我的名称部分出现 null 值错误,我不确定原因。 What am I missing?我错过了什么?

My PHP file returns我的 PHP 文件返回

{"names":["john doe","jane doe"],"ids":["123","223"]}

It seems to be just ending here Uncaught TypeError: Cannot read property '0' of undefined so my sub0 is killing me.它似乎只是在这里结束Uncaught TypeError: Cannot read property '0' of undefined所以我的 sub0 正在杀了我。

You could prob use the $.getJSON facade that jQuery provides, this will setup all the required ajax params for a standard JSON request:您可以使用 jQuery 提供的$.getJSON facade,这将为标准 JSON 请求设置所有必需的 ajax 参数:

$.getJSON('test.php', function(response) {
    alert(response.names[0]);   // john doe
}); 

However i think the route of the issue is that 1) your server may not be returning the correct response codes and/or the correct headers (ie: JSON data) - however the above method at least for the latter should force this conclusion.但是我认为问题的根源是 1) 您的服务器可能没有返回正确的响应代码和/或正确的标头(即:JSON 数据) - 但是至少对于后者的上述方法应该强制得出这个结论。

See: http://api.jquery.com/jQuery.getJSON参见: http://api.jquery.com/jQuery.getJSON

It looks like the problem is that you're using the complete callback instead of the success callback:看起来问题是您使用的是完整回调而不是成功回调:

function getList(){
    $.ajax({  
        type: "GET", 
        url: 'test.php', 
        data: "",  
        success: function(data) { /* success callback */
            var test = jQuery.parseJSON(data);
            alert(test.names[0]);
            alert("here");
        }
    },
    "json");
}
getList();

From jQuery AJAX Docs:来自jQuery AJAX文档:

success(data, textStatus, jqXHR)成功(数据,文本状态,jqXHR)

A function to be called if the request succeeds.如果请求成功,将调用 function。 The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; function 得到传三 arguments:从服务器返回的数据,根据dataType参数格式化; a string describing the status;描述状态的字符串; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions.和jqXHR(在jQuery 1.4.x,XMLHttpRequest)object。从jQuery 1.5开始,成功设置可以接受函数数组。 Each function will be called in turn.每个function都会依次调用。 This is an Ajax Event.这是一个 Ajax 事件。

complete(jqXHR, textStatus)完成(jqXHR,文本状态)

A function to be called when the request finishes (after success and error callbacks are executed).请求完成时调用 function(执行成功和错误回调后)。 The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). function 通过了两个 arguments:jqXHR(在 jQuery 1.4.x,XMLHTTPRequest 中)object 和一个对请求状态进行分类的字符串(“成功”、“未修改”、“错误”、“超时”、“中止”或“解析器错误”)。 As of jQuery 1.5, the complete setting can accept an array of functions.截至jQuery 1.5,完整设置可以接受函数数组。 Each function will be called in turn.每个function都会依次调用。 This is an Ajax Event.这是一个 Ajax 事件。

jQuery wants to know what kind of data to expect as a response, otherwise it wont know how to parse it. jQuery 想知道期望什么样的数据作为响应,否则它不知道如何解析它。

So, as has been said before here, you tell jQuery using the dataType = 'json' attribute.因此,如前所述,您使用dataType = 'json'属性告诉 jQuery。

function getList() {
    $.ajax({  
        type: "GET", 
        url: 'test.php', 
        data: "",  
        dataType: "json",
        success: function(data) { 
            console.log(data);
        }
    });
}

On top of this it is a good idea to have PHP present its content as json rather than html. You use the header for this by setting header('Content-type: application/json');最重要的是,让 PHP 将其内容显示为 json 而不是 html 是个好主意。为此,您可以通过设置header('Content-type: application/json');使用 header。 before any output in your PHP script.在您的 PHP 脚本中的任何 output 之前。 So:所以:

$names = array('john doe', 'jane doe');
$ids = array('123', '223');

$data['names'] = $names;
$data['ids'] = $ids;

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

echo json_encode($data);

You should pass all parameters for ajax() function in single object. So, there should be "dataType" option.您应该在单个 object 中传递 ajax() function 的所有参数。因此,应该有“dataType”选项。 Also, if you set data type explicitly, jQuery will parse JSON data for you.此外,如果您明确设置数据类型,jQuery 将为您解析 JSON 数据。 Complete callback will receive parsed JavaScript object as parameter.完成回调将接收解析后的 JavaScript object 作为参数。

function getList() {
    $.ajax({  
        type: "GET", 
        url: 'test.php', 
        data: "",  
        dataType: "json",
        success: function(test) { 
            alert(test.names[0]);
            alert("here");
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM