繁体   English   中英

在函数中返回json结果

[英]Returning json result in function

我从ajax请求得到json响应

我想将json结果返回给var obj getTwitterVal()函数调用。 然后在$('#loginTwitter').click(function data() {}获取名称和ID。如何实现?

以下代码返回警报“未定义”

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); 

它不是那样工作的。 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);
    });
}

使用@freakish提到的异步ajax。 另外,如果您已经在使用jquery,则让它也使其ajax起作用。 像这样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM