无法使用jquery$.ajax访问从php页面检索到的json数据
Unable to access json data retrieved from php page using jquery $.ajax
如何在JavaScript中访问此json数据。当我提醒它时,结果是undefined
这是jQuery代码
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
这是PHP代码
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
我已经独立测试了PHP文件,json数据输出如下:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
您可以通过访问数据
data[0].Result
它是一个Object,而不是数组。
所以data[0]['Result']
不是的正确方式
编辑:由于你有更多的对象,你必须这样做一个循环:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
当你看到类似的东西时
{
"foo":"bar",
...
}
你可以通过与上面相同的方式访问它:
name_of_the_object.foo
将具有值"bar"
尝试添加解析JSON。我已补充。现在它可能是工作。
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});
相关文章:
- 如何通过php页面将数据库值检索到jquery自动完成框中
- 通过ajax将坐标传递到php服务器端,并在处理后检索到javascript
- 如何从php返回的JSON中检索值
- PHP无法检索request.send
- Php无法检索动态生成的文本字段
- 在php中的同一网页上检索所选下拉项的值,并使用其他数据将其发布到其他表单
- 检索php值并在javascript中使用它
- 使用JSON检索PHP数组,并使用javascript中的数组来填充播放列表
- 从ajax中检索php数组
- 在 JSON 中使用和检索 PHP 变量
- 如何在特定的时间跨度使用 AJAX 检索 php 表单
- 如何避免在调试时检索PHP脚本的文字内容
- 检索PHP变量到Bootstrap Modal
- 使用隐藏输入是在外部JavaScript文件中检索php变量的有效方法吗?
- 如何运行JQuery后的php主页面包括php子页面
- 如何使用JavaScript检索PHP$_GET
- 使用javascript onload()和ajax来检索php数组
- 使用 JavaScript Ajax JSON 检索 PHP 数组时出错
- 使用jQuery's .get()检索PHP数据
- 通过AJAX检索PHP JSON数据-正确的数据请求结构