为什么我的服务器代码ajax调用返回用双引号引起来的响应? [英] Why is my server code ajax call returning a response wrapped in double-quotes?

查看:106
本文介绍了为什么我的服务器代码ajax调用返回用双引号引起来的响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从JavaScript到apx页面的webmethod进行ajax调用.由于某种原因,我返回的字符串用双引号引起来.我尝试将它们剥离,但是由于某种原因,替换仅替换了第一个.没有引号将字符串包装在服务器端.

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"

有什么想法吗?

推荐答案

首先,如果您担心看到的是"mystring"而不是" mystring(双引号而不是单引号),那是因为开发人员控制台会自动在字符串值周围显示引号,如果您的字符串实际上包含"quote"字符,则可能会造成混淆.您在控制台中看到的外部引号不存在,只有内部引号存在.

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.

接下来,根据JSON规范( http://www.json.org/),JSON字符串以引号开头和结尾.如果您想解析json字符串,请使用:

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.

如果您正在使用JSON对象,正如您的响应标头(application/json)所表明的那样,我强烈建议您使用JSON.parse

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

这篇关于为什么我的服务器代码ajax调用返回用双引号引起来的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆