[英]Convert Json encoded data to javascript array and access value by index
I am getting json response from ajax like this 我从像这样的ajax得到json响应
echo json_encode($data);
Ajax code: Ajax代码:
$.ajax({
url:"PaymentSlip/check",
data:{val:val},
type: 'POST',
success:function(ajaxresult)
{
$("#jgoli").html(ajaxresult);
}
});
Result I am getting is: 我得到的结果是:
[{"paymentId":"2","paymentLabNo":"MR-622-040618",paymentTestId":"1"}]
Now I want to access my json array in javascript by index like 现在我想按索引访问javascript中的json数组
ajaxresult[0] = 2; i.e paymentId=2
ajaxresult[1] = 2; i.e paymentLabNo=MR-622-040618
How would I achieve that? 我将如何实现?
Note: I have tried many examples on stackoverflow, I know this question must have answered earlier. 注意:我已经在stackoverflow上尝试了许多示例,我知道这个问题一定已经回答了。 But I am still stuck. 但是我仍然被困住。 Any help would be appreciated. 任何帮助,将不胜感激。
What you are getting is a string of encoded JSON, to use it as an object you must parse it. 您得到的是一个已编码的JSON字符串,要将其用作对象,您必须对其进行解析。
$(document).ready(function(){ var data = [{"paymentId":"2","paymentLabNo":"MR-622-040618","paymentTestId":"1"}]; //Loop on the object as key=>value $.each(data, function(key, value){ //And diplay it in the result div $('#result').append('<p>'+data[key]['paymentId']+'</p>'); $('#result').append('<p>'+data[key]['paymentLabNo']+'</p>'); $('#result').append('<p>'+data[key]['paymentTestId']+'</p>'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <div id="result"></div>
$(document).ready(function(){
$.get("ajax_call.php", function(data){
//console.log(data);
var result = JSON.parse(data);
$.each(result, function(key, value){
$('#data').append('<tr><td>'+result[key]['username']+'</td><td>'+result[key]['email']+'</td><td>'+result[key]['mobile']+'</td></tr>');
console.log(result[key])
});
});
});
$.ajax({
url:"PaymentSlip/check",
data:{val:val},
type: 'POST',
datatype: "json", // add this
success:function(ajaxresult)
{
// access return results as
//ajaxresult[0].paymentId;
//ajaxresult[0].paymentLabNo;
//ajaxresult[0].paymentTestId;
//$("#jgoli").html(ajaxresult);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.