简体   繁体   English

处理ajax成功响应

[英]Handling ajax success response

PHP: lockState.php PHP:lockState.php

require '../dbconn.php';
$query = mysql_query("select id, lockState,name from register_db where Id=1");
$items = array();
while ($row = mysql_fetch_object($query)) {
    array_push($items, $row);
}
echo json_encode($items);

Result from query 查询结果

[{"id":"1","lockState":"No","name":"Local Application"}]

Index.php Index.php

$.ajax({
            type: "POST",
            url: "feed/lockState.php",
            data: ({id: 1}),
            cache: false,
            dataType:"json",
            success: function (response) {
                alert(JSON.stringify(response));  // [{"id":"1","lockState":"No","name":"Local Application"}]
                alert(response.name); //***undefined***
                  if(response.name=='Local Application'){
                     callMyFunction(response.name);
                   }
          },
            error: function () {
               alert("Oops..!! Something wrong!);

            }
        });

I'm totally lost where I'm doing wrong in using 'Success' response. 我在使用“成功”响应做错的地方完全迷路了。 Even I tried to JSON.parse(response) and tried to access the key:value, but still same undefined . 甚至我都尝试JSON.parse(response)并尝试访问key:value,但仍未undefined Please help. 请帮忙。

response[0].name将为您提供帮助。

Look at your PHP. 查看您的PHP。 See $items = array(); 参见$items = array(); where you create an array. 在这里创建数组。

Look at the data you are getting. 查看您获取的数据。 See the [ and ] around it. 请参]周围的[]

You have an array containing an object. 您有一个包含对象的数组 You need to read the first value out of that array. 您需要从该数组中读取第一个值。

var object = response[0];
var name = object.name;

The way you tried would work if the response was: 如果响应为:

{"id":"1","lockState":"No","name":"Local Application"}

But your response is: 但是您的回答是:

*[*{"id":"1","lockState":"No","name":"Local Application"}*]*

The brackets mean the response is an array, [], containing an object, {}; 方括号表示响应是一个数组[],包含一个对象{};

As others have mentioned; 正如其他人所提到的; the way to retrieve values out of an array can be done by using array_variable[0] to for example select the first. 可以通过使用array_variable [0]例如选择第一个来完成从数组中检索值的方法。

In your example try this: 在您的示例中尝试以下操作:

 alert(response[0].name); //***undefined***

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

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