javascript - 使用 eval 解析 JSON 字符串

标签 javascript ajax json parsing eval

function ajaxFunction(){
var ajaxRequest;  // The variable that makes Ajax possible!

try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser is too old to run me!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {

$("#resultTXT").val(data);

var response = data;

var parsedJSON = eval('('+response+')');
alert('parsedJSON:'+parsedJSON);

var result=parsedJSON.result;

var count=parsedJSON.count;

alert('result:'+result+' count:'+count);




},'json'

);      }
}
    ajaxRequest.open("POST", "userfind.php", true);
    ajaxRequest.send(null); 
}

Blockquote so I have got my above code, with your guys help. the above code will fill out the txtbox with a string, but i am not able to access each element of the string. The string is an array paged from a PHP file using Jsone_encode.

数组是这样的。 [{"user_id":"2790","freelancer_name":"","order_id":"9121","orderamount":"0.00"

我想做的是编写这样的代码:

    document.getElementById("_proId").value = user_id;
document.getElementById("_buyerSt").value = freelancer_name;
document.getElementById("_buyerDesc").value = order_id;
document.getElementById("_mngSt").value = orderamount;
  ... etc

Blockquote so my problem is how to split the string and fetch the data. these 2 vars

var result=parsedJSON.result;

    var count=parsedJSON.count;
    alert (""+result);
    alert (""+count);

仅提醒我未定义。

请帮我从字符串中获取数据。

该数组是从 mysql 表中获取的,而且它很大

最佳答案

1.看起来没有充分的理由自己使用 eval 来解析 json。

您可以使用经过验证的 JSON 库,如 json2.jsJSON-js

2.您的 JSON [ {"user_id":"123", ... }, {... }, {...} ] 将被解析为数组。

使用 for every 来迭代数组中的对象。

关于javascript - 使用 eval 解析 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11443745/

相关文章:

javascript - 单击外部按钮/下拉菜单时,下拉菜单不会关闭

php - AJAX:打开另一个div中的内容

javascript - 请求 ASP.NET 页面异步 (ajax) 更新而不将整个页面发送到服务器

c# - 解析 Json 字符串

json - Apache Nifi - 从 Avro 中提取属性

java - 如何在 strings.xml 中设置从 JSON 消耗的变量

javascript - 使用内容安全策略阻止 Internet Explorer 11 上的内联 JavaScript

php - 由于 PHP 包含和 MySQL 查询的回显,Javascript 中出现新行

javascript - 如何在单击事件的动态加载内容中绑定(bind)事件?

javascript - 函数的子函数作为原型(prototype)