【问题标题】:GET key value from AJAX response从 AJAX 响应中获取键值
【发布时间】:2014-10-31 18:56:24
【问题描述】:

我正在对一个 php 进行跨域调用,它返回:

response=2&count=15&id=84546379&firstname=adsa&emailstatus=

我想挑出response和id的值,但不知道怎么选,我的代码如下:

**

xhr.request({
                    url: "../promo_getstate2.php",
                    method: "POST",
                    data: {
                      email: emailaddress,
                      country: country,
                      lang: lang,
                      source: '1312_XMAS_dly'
                    }
                }, function(response){
                   getstate = response['response'];
                   regID = response['id'];
                   console.log(getstate)
                    console.log(regID)
})

但它没有得到这些值。我该怎么做?

回复是:

" response=2&count=15&id=84546379&firstname=adsa&emailstatus="

**

【问题讨论】:

标签: php jquery ajax


【解决方案1】:

您可以在响应中创建一个包含所有参数的params 对象,如下所示:

function parseResponse(str) {
    var arr = str.split("&");
    var temp, params = [];
    for(var i = 0; i < arr.length; ++i) {
        temp = arr[i].split("=");
        params[temp[0]] = temp[1];
    }
    return params;
}

var values = parseResponse("response=2&count=15&id=84546379&firstname=adsa&emailstatus=")

然后您可以按以下方式访问值:

values['response']; // 2

values['id']; // 84546379

【讨论】:

  • 你能分享你传递给函数的字符串吗?
【解决方案2】:

代码如下:

<Script language="javascript">
        var vars=GetRequest("response=2&count=15&id=84546379&firstname=adsa&emailstatus=");
        document.write(JSON.stringify(vars));

        function GetRequest(v) {
           var url = "?"+v;//location.search;
           var theRequest = new Object();
           if (url.indexOf("?") != -1) {
              var str = url.substr(1);
              strs = str.split("&");
              for(var i = 0; i < strs.length; i ++) {
                 theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
              }
           }
           return theRequest;
        }
        </script>

然后你可以得到值。例如结果的json是

{"response":"2","count":"15","id":"84546379","firstname":"adsa","emailstatus":""}

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多