Why is my server code ajax call returning a respon

2020-07-06 01:52发布

问题:

I am doing an ajax call from my javascript to an aspx page's webmethod. The string I'm returning is wrapped in double-quotes for some reason. I tried stripping them out, but the replace only replaced the first one for some reason. There are no quotes wrapping the string on the server-side.

        var req = new XMLHttpRequest();
        var url = document.URL;
        // strip pound sign off the end
        var poundIndex = url.lastIndexOf('#');

        if (poundIndex === url.length - 1) {
            url = url.substring(0, poundIndex);
        }
        url += '/SignOn';
        req.open('post', url, false);
        req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        req.send();

        var serverResponse = req.responseText.replace('"', '');

This is what I'm doing on the server:

Return System.Configuration.ConfigurationManager.AppSettings("url").ToString + "?token=" + HttpContext.Current.Session("Token").ToString() + "&aid=ca"

Any ideas?

回答1:

Firstly, if you're concerned that you see ""mystring"" instead of "mystring" (double quotes instead of single quotes), that's because the developer console automatically displays quotes around string values, which can be confusing if your string actually contains the "quote" character. The outer quotes you see in the console aren't there, only the inner quotes are.

Next, according to the JSON spec (http://www.json.org/) JSON strings start and end with quotes. If you wish to parse json strings, use:

var str = JSON.parse(req.responseText);

If you simply wish to get rid of all quotes in a string, try

var str = req.responseText.replace(/\"/g, "");

Note that the latter gets rid of ALL quotes, including (escaped) quotes in the middle of the string.

If you're working with JSON objects, as your response header (application/json) seems to indicate, I strongly recommend working with JSON.parse