如何将 Json 对象(或字符串数​​据)从 Javascript xmlhttprequest 发送到 MVC 控制器 [英] How to send Json object (or string data) from Javascript xmlhttprequest to MVC Controller

查看:28
本文介绍了如何将 Json 对象(或字符串数​​据)从 Javascript xmlhttprequest 发送到 MVC 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP.NET MVC 中创建了一个 Web 应用程序,并尝试通过 Javascript AJAX 调用控制器.在 Jquery 中,我们可以发送一个 json 对象,MVC 模型绑定器会自动尝试创建一个 .NET 对象并作为参数传入控制器.

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 的网络工作者.所以我通过 vanilla xmlhttprequest 对象进行 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?

我使用了 xmlhttprequest 的 send 方法,但模型对象在控制器中为 null :(

I used the xmlhttprequest's send method but the model object comes as null in the controller :(

推荐答案

您应该能够使用 JSON2 对其进行字符串化并将 Content-Type 标头设置为 application/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.

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));

这篇关于如何将 Json 对象(或字符串数​​据)从 Javascript xmlhttprequest 发送到 MVC 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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