Javascript 从AJAX响应中提取值
我的php代码如下Javascript 从AJAX响应中提取值,javascript,php,jquery,arrays,ajax,Javascript,Php,Jquery,Arrays,Ajax,我的php代码如下 if ($data = $user->fetch()) { echo json_encode(array("output" => $data)); } else { echo json_encode(array("output" => $data)); } success: function(response) { alert(response); //shows me [object Object] alert
if ($data = $user->fetch())
{
echo json_encode(array("output" => $data));
}
else
{
echo json_encode(array("output" => $data));
}
success: function(response)
{
alert(response); //shows me [object Object]
alert(response[0].output); // shows me nothing
alert(response[0]); //shows me undefined
alert(JSON.stringify(response)); //shows me {"output":false}
//I would like to get only true or false
}
我的javascript代码如下
if ($data = $user->fetch())
{
echo json_encode(array("output" => $data));
}
else
{
echo json_encode(array("output" => $data));
}
success: function(response)
{
alert(response); //shows me [object Object]
alert(response[0].output); // shows me nothing
alert(response[0]); //shows me undefined
alert(JSON.stringify(response)); //shows me {"output":false}
//I would like to get only true or false
}
从这篇文章()中,我知道[object]基本上是一个数组
从这篇文章()中,我得到了以下文字
“正如您所看到的,您的响应以[开头,以]结尾,因此您的响应是一个数组
然后,在数组内部获得对象(以{开始,以}结束)
因此,您的数据是一个数组,可以使用数据[x](x是索引)访问该数组,并且可以使用.dot符号访问选定对象的每个成员:.word、.text等
因此,在您的情况下,如果只有一个结果,则可以执行数据[0]。word。“
在这种情况下,我应该使用警报(响应[0]。输出)获得预期结果强>
但我没有得到那个结果。在这方面有人能帮我吗 首先,确保已明确设置要接收JSON:
dataType: 'JSON',
然后尝试通过以下方式访问它们:
success: function(response) {
console.log(response.output);
// kindly open your console browser to see contents
// i think this is F12
if(response.output) {
// do something if true
} else {
// do something if false
}
}
你也可以试试这个:
success: function(response) {
// check your console
console.log(response);
//this two will give you same result
console.log(response.output);
console.log(response['output']);
//either of this two
var output = response.output;
var output = response['output'];
if(output){
//code here
}
}
您将通过response.output获得它
var data=response.output
。现在data[0]
是$data和其他数据的第一个元素。