如何从Javascript xmlhtt prequest发送JSON对象(或字符串数据)MVC控制器 [英] How to send Json object (or string data) from Javascript xmlhttprequest to MVC Controller
问题描述
我创建了ASP.NET MVC的Web应用程序,并试图调用通过JavaScript AJAX的控制器。 jQuery中,我们可以发送的MVC模型绑定自动尝试创建.NET对象并通过在控制器作为一个参数的JSON对象。
I created a web application in ASP.NET MVC and trying to call a controller through Javascript AJAX. In Jquery we can send a json object which MVC Model Binder automatically tries to create a .NET object and pass in the controller as an argument.
不过我使用的是网络工作者中不能使用jQuery的。所以,我提出通过香草xmlhtt prequest对象AJAX调用。有没有一种方法,通过这种方法来发送JSON对象?
However I am using a web workers in which jquery cannot be used. So I am making the AJAX call through the vanilla xmlhttprequest object. Is there a a way to send the Json object through this method?
我用xmlhtt prequest的发送方法,但模型对象在控制器当属无效:(
I used the xmlhttprequest's send method but the model object comes as null in the controller :(
推荐答案
您应该只能够使用JSON2来字符串化它和内容类型
头设置为应用程序/ JSON
当你的职位。
You should just be able to use JSON2 to stringify it and set the Content-Type
header to application/json
when you do the post.
<一个href=\"http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js\">http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js
您会做这样的事情:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Controller/Action');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(JSON.stringify(myData));
这篇关于如何从Javascript xmlhtt prequest发送JSON对象(或字符串数据)MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!