jsonP数据出错

Posted

技术标签:

【中文标题】jsonP数据出错【英文标题】:getting error on jsonP data 【发布时间】:2018-04-12 07:59:03 【问题描述】:

我正在尝试获取 jsonp 数据,但出现错误

$.ajax(
                type: "GET",
                url: 'http://localhost:59672/RestServiceImpl.svc/getallemp',
                contentType: "application/json",
                dataType: "jsonp",
                jsonpCallback: 'callback',
                success: function (data) 
                    console.log(data);//i am getting Error

                ,
                error: function (xhr) 
                    console.log(xhr);
                
            );

下面是我的json回复

"success":"[\"usercode\":2,\"usercode\":23,\"usercode\":24,\"usercode\":25,\"usercode\":26,\"usercode\":27,\"usercode\":28,\"usercode\":29,\"usercode\":30,\"usercode\":31]"

然后我得到以下错误

Uncaught SyntaxError: Unexpected token :

我正在使用 WCF Restful 服务 以下是服务代码

[WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "getallemp")]
        [return: MessageParameter(Name = "success")]
        string GetAllEmployee();

Response

【问题讨论】:

您可以尝试使用 WebMessageBodyStyle.Bare 吗? ***.com/questions/32098418/… @OguzOzgul,更改后我得到以下响应 readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, ... 响应在哪里?这看起来不像是对我的回应。 这是我在 console.log(date) 上得到的“readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, ...” @OguzOzgul,在 google chrome 网络上,我得到关注 ""[\"usercode\":2,\"usercode\":23,\"usercode\":24 ,\"usercode\":25,\"usercode\":26,\"usercode\":27,\"usercode\":28,\"usercode\":29 ,\"usercode\":30,\"usercode\":31]"" 【参考方案1】:
protected void Application_BeginRequest(object sender, EventArgs e)

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    

【讨论】:

以上是关于jsonP数据出错的主要内容,如果未能解决你的问题,请参考以下文章

为啥 jQuery ajax jsonp 请求会出错?

JSONP 请求在 Angular 应用程序中给出 404

ph解码jsonp数据

接口测试返回数据为JSONP格式时如何处理

Python获取jsonp数据

封装 jsonp请求数据的方法