返回json导致函数

时间:2014-01-30 07:40:46

标签: javascript json

我从ajax请求获得json响应

我想在var obj中将json结果返回给getTwitterVal()函数调用。然后在$('#loginTwitter').click(function data() {}中获取姓名和身份证明。这个怎么样?

以下代码返回警报'undefined'

function getTwitterVal()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status==200)
        {
            var result = xmlhttp.responseText;
            //result looks like this : {"name": jack,"id":1}
            //obj = JSON.parse(result);

            return result;
        }
    }
    xmlhttp.open("POST","redirect.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send();
    // api_call();
}

$('#loginTwitter').click(function data() {

    var obj = getTwitterVal();
    alert(obj.name);                    // I want retrieve name and id both value here
 }

更新的代码

function getTwitterVal(clb)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    }
    xmlhttp.onreadystatechange=function()
    {
                var result = xmlhttp.responseText;
                var obj = JSON.parse(result);
                clb(obj);
    }
    xmlhttp.open("POST","redirect.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send();
    // api_call();
}



$('#loginTwitter').click(function data() {
    getTwitterVal(function(obj) {
        alert(obj.name);
    });
});

给出错误

SyntaxError: JSON.parse: unexpected character var obj = JSON.parse(result); 

2 个答案:

答案 0 :(得分:4)

它不起作用。 AJAX调用是异步的。虽然可以使它同步,但你永远不应该这样做(因为它会阻止页面上的所有其他脚本)。而是将回调传递给getTwitterVal

function getTwitterVal(clb) {
    // some code
            if (xmlhttp.readyState == 4 && xmlhttp.status==200)
            {
                var result = xmlhttp.responseText;
                var obj = JSON.parse(result);
                clb(obj);
            }
    // other code
}

然后

$('#loginTwitter').click(function data() {
    getTwitterVal(function(obj) {
        alert(obj.name);
    });
}

答案 1 :(得分:1)

使用异步ajax,如@freakish所述。另外,如果你已经使用了jquery,那么让它也可以使用它的ajax。这样的事情:

$('#loginTwitter').click(function() {
    $.post(
        'redirect.php',
        function(data) {
            var obj = JSON.parse(data);
            alert(obj.name);
        });
});