jQuery从ajax响应中读取数组

时间:2015-08-21 06:22:39

标签: php jquery ajax json

这是如此基本但我已经被困了一个多小时,因为我找不到一个确切的例子。感谢您提供的任何链接。

我在php中构建JSON,如下所示:

return json_encode(['error' => 'customer number not found']);

它返回一个如下所示的基本数组(来自inspect):

{error: 'customer number not found'}

我通过jQuery调用了Ajax / getJSON:

   $.getJSON( url, function( response ) {

        $.each(response[0], function(key, value) {

            // Check response for errors
            if (key == "error") {

                // display message
                $(message_area).innerHTML = value;

                // Show the error message
                $(message_area).show();

            };

        });

    });

我只想检查第一个值,然后显示第二个值并显示容器。上面的代码给了我

Uncaught TypeError: Cannot read property 'length' of undefined

5 个答案:

答案 0 :(得分:2)

而不是使用$.each,更好的做同样事情的方法(给定当前场景)是检查response.error是否存在。 :)

将您的代码更改为

 $.getJSON( url, function( response ) {
    if (response.error){
        $(message_area).html(response.error);
        // Show the error message
        $(message_area).show();
    } else{
        // No error, do your success stuff
    }
 });

附录:

首先,您从PHP获得的response不是数组。这是一个对象。检查对象中的现有属性比循环遍历对象的键和值更明智,更直观。

第二 - 你的$(message_area)是一个jQuery对象。您不能像设置它一样直接为jQuery对象设置innerHTML。假设message_area仅选择一个元素,这样做的方法是 $(message_area)[0].innerHTML = "your value";

但是如果你正在使用jQuery,那么遵循jQuery的精神更为明智,所以你应该做的是

$(message_area).html('your value');

希望有所帮助。 :)

答案 1 :(得分:1)

尝试使用response代替response[0]

您只是访问数组的第一个元素而不是循环遍历它。

长度错误是因为单个第一个项目没有长度。

答案 2 :(得分:1)

我更愿意这样做:

$.getJSON( url, function( response ) {
  for(var key in response) {
    if(!response.hasOwnProperty(key)) continue;
    if(key === "error") {
      // display message
      $(message_area).innerHTML = response[key];
      // Show the error message
      $(message_area).show();
      break; // exit the loop!
    }
  }
});

在这种情况下,它会遍历一个对象的键,如果是JSON,它会很好用。

答案 3 :(得分:0)

{error: 'customer number not found'}不是数组,它是一个简单的对象。因此,您需要使用response代替response[0]

另外innerHTML是DOM元素的属性而不是jQuery对象。使用jQuery对象设置HTML时使用.html()函数。

使用

$.getJSON( url, function( response ) {
    //Remove [0]
    $.each(response, function(key, value) {
        if (key == "error") {

            //Use .html() method
            $(message_area).html(value);

           $(message_area).show();
        };
    });
});

答案 4 :(得分:0)

在PHP中:

return json_encode(array('error' => 'customer number not found'));

在你的jQuery .done()函数中:

.done(function(response){
    response = $.parseJSON(response);
    $.each(response, function(key, value) {
        if(key == 'error') {
            // display message
            $(message_area).html(value);

            // Show the error message
            $(message_area).show();
        }
    });
});