简体   繁体   中英

GET key value from AJAX response

I'm making a cross domain call to a php which returns this:

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

I want to pick out the values of response and id, but not sure how, my code is as follows:

**

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

but it's not geting those values. How do I do this?

The response is:

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

**

What you can do is create a params object of all parameters in the response as shown below:

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=")

You can then access values as:

values['response']; // 2

values['id']; // 84546379

Code as that:

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

Then you can get the values. For example, the json of the result is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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