简体   繁体   English

MVC4 AJAX发布JSON

[英]MVC4 AJAX post JSON

this is my function, where i post json only 这是我的功能,我只发布json

function test() {
            var imgFile = document.getElementById('image');
            //            var imgData = JSON.stringify(getBase64Image(imgElem));
            //var imgData = Convert.FormBase64String(imgElem);

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: "http://localhost:59102/Contacts/AddContact",
                data: "json=" + "{\"token\":\"8mVm/nS1OfpU+nlQLbJjqXJ7kJI=VyLGI2GEKkGgtDt0babrAw==\"}",

                success: function (returnPayload) {
                    console && console.log("request succeeded");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console && console.log("request failed");
                },

                processData: false,
                async: false
            });

and i dont know how to add to my data, image, i need to post json and image 而且我不知道如何添加到我的数据,图像中,我需要发布json和图像

this is my controller 这是我的控制器

[HttpPost]
        [AllowAnonymous]
        public JsonResult AddContact(string json, HttpPostedFileBase file)
        {}

You can't upload files via AJAX (by design) unless you use a plugin that utilises other 'technology' such as flash, or iframes - this is a security measure as JavaScript reading local files on your machine would not be the best idea 除非使用使用Flash或iframe等其他“技术”的插件,否则您无法通过AJAX上传文件(按设计)-这是一种安全措施,因为JavaScript读取计算机上的本地文件不是最佳方法

There's an option here: http://jquery.malsup.com/form/ 这里有一个选项: http : //jquery.malsup.com/form/

...otherwise I suggest looking up one of the many other alternatives! ...否则,我建议您查找其他多种选择之一!

after you getting the data to a base 64 , your json should be an object from your controller your json should be something like this 在将数据获取到base 64之后,您的json应该是控制器中的对象,而json应该是这样的

{"json":"something here that is a string","file":"some file"}

Also on the client side you should have an object on which you invoke JSON.stringify() 同样在客户端,您应该有一个对象,您可以在该对象上调用JSON.stringify()

var ob = {json:imageDataAsBase64,file:fileDataAsBinary} var ob = {json:imageDataAsBase64,file:fileDataAsBinary}

although I dont see the reason to send both. 尽管我看不到发送两者的理由。 if what you need is just transafering an image that you just need to get the image as base64 and post it as a json 如果您只需要传输图像,则只需将图像获取为base64并将其发布为json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM