jquery ajax xmlhttprequest cannot load,json - XMLHttpRequest cannot load an URL with jQuery - Stack ...

陶文林
2023-12-01

Found a possible workaround that I don't believe was mentioned.

Basically as long as you use forms/url-encoded/plain text content types you are fine.

$.ajax({

type: "POST",

headers: {

'Accept': 'application/json',

'Content-Type': 'text/plain'

},

dataType: "json",

url: "http://localhost/endpoint",

data: JSON.stringify({'DataToPost': 123}),

success: function (data) {

alert(JSON.stringify(data));

}

});

I use it with ASP.NET WebAPI2. So on the other end:

public static void RegisterWebApi(HttpConfiguration config)

{

config.MapHttpAttributeRoutes();

config.Formatters.Clear();

config.Formatters.Add(new JsonMediaTypeFormatter());

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));

}

This way Json formatter gets used when parsing plain text content type.

And don't forget in Web.config:

Hope this helps.

 类似资料: