Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Ajax从web服务返回JSON而不是XML,同时';contentType';是';假';_Javascript_Jquery_Asp.net_Ajax_Web Services - Fatal编程技术网

Javascript 使用Ajax从web服务返回JSON而不是XML,同时';contentType';是';假';

Javascript 使用Ajax从web服务返回JSON而不是XML,同时';contentType';是';假';,javascript,jquery,asp.net,ajax,web-services,Javascript,Jquery,Asp.net,Ajax,Web Services,我调用AJAX将图像文件发送到我的一个web服务(.asmx)方法。一切正常,但问题是web服务返回XML而不是JSON,因为我必须将'contentType'设置为'false',否则无法发送文件。(如果我将contentType设置为application/json;charset=utf-8,它将返回json,但我无法返回,因为我正在发送一个文件。) 这是我的JavaScript: function setAvatar(imageFile, successCallback) { var f

我调用AJAX将图像文件发送到我的一个web服务(.asmx)方法。一切正常,但问题是web服务返回XML而不是JSON,因为我必须将
'contentType'
设置为'
false'
,否则无法发送文件。(如果我将
contentType
设置为
application/json;charset=utf-8
,它将返回json,但我无法返回,因为我正在发送一个文件。)

这是我的JavaScript:

function setAvatar(imageFile, successCallback) {
var formData = new FormData();
formData.append("UploadedAvatar", imageFile);
$.ajax({
    type: "POST",
    url: "/Services/UserService.asmx/SetAvatar",
    contentType: false,
    processData: false,
    dataType: 'json',
    data: formData,
    success: function (result) {
        alert(result.d);
        alert(result.d.IsSuccessful);
        if (typeof successCallback === 'function')
            successCallback(result);
    }
});
以及web服务方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Result SetAvatar()
{
    HttpPostedFile postedFile = HttpContext.Current.Request.Files["UploadedAvatar"];
    Image avatar = Image.FromStream(postedFile.InputStream, true, true);
    avatar = new Bitmap(avatar, new Size(150, 150));
    avatar.Save(Path.Combine(path, $"Avatar-Small.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);

    return new Result(true, Messages.AvatarSavedSuccessfully);
}

在请求使用JSON时,设置
Accept
标题

$.ajax({
    type: "POST",
    url: "/Services/UserService.asmx/SetAvatar",
    headers: { //SET ACCEPT HEADER
        Accept : "application/json; charset=utf-8",
    },  
    contentType: false,
    processData: false,
    dataType: 'json',
    data: formData,
    success: function (result) {
        alert(result.d);
        alert(result.d.IsSuccessful);
        if (typeof successCallback === 'function')
            successCallback(result);
    }
});
在服务器端,使用
Json.Net
可以序列化结果

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SetAvatar() {
    HttpPostedFile postedFile = HttpContext.Current.Request.Files["UploadedAvatar"];
    Image avatar = Image.FromStream(postedFile.InputStream, true, true);
    avatar = new Bitmap(avatar, new Size(150, 150));
    avatar.Save(Path.Combine(path, $"Avatar-Small.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);

    var result = new Result(true, Messages.AvatarSavedSuccessfully);
    return JsonConvert.SerializeObject(result);
}

这将允许响应为所需类型

您需要更新
.NET
代码并添加
选项。RespectBrowserAcceptHeader=true

services
    .AddMvc(options => {
        options.RespectBrowserAcceptHeader = true;
    })
    //support application/xml
    .AddXmlDataContractSerializerFormatters()
    //support application/json
    .AddJsonOptions(options => {
        // Force Camel Case to JSON
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });
dataType:'json'
将自动添加
Accept
标题,如下所示

"accept":"application/json, text/javascript, */*; q=0.01"
如果您特别想要
application/json
,那么您需要在ajax选项中添加以下内容

headers: {
  Accept : "application/json; charset=utf-8"
}

在我的头撞在墙上好几天之后,我终于想出了属于我的解决办法

虽然没有其他帮助,但我使用了它,它非常有效:

  • 将方法的返回类型更改为
    void

  • 然后,您不需要在方法中编写
    return
    语句,而需要这样做来返回一个值:

    Context.Response.ContentType = "application/json; charset=utf-8";
    Context.Response.Write(new JavaScriptSerializer().Serialize(new YourData()));
    
  • 之后,您可以使用Ajax调用的
    success
    事件轻松获得结果:

    success: function (result) {
        alert(result.Property); // Note: Don't use result.d here
    }
    

  • 看看我的答案。您试图返回一个对象,但必须先对其进行序列化。在此之后,您可能可以删除contentType并使用默认设置。@wazz如果没有帮助,请确保您有
    options.reserverBrowserAcceptHeader=true,因此返回类型基于
    Accept
    标题。当我添加此代码时,会出现ajax错误,因为服务方法的结果不正确JSON@AmirHosseinAhmadi结果当前看起来像什么结果仍然是一个XML文档:(@AmirHosseinAhmadi,即使在服务器上有最新的建议?显示结果的一个片段。它是XML包装JSON吗?第二个建议也返回XML::(我今天要讨论一个实例,我应该把代码放在哪里?换句话说,‘services’变量是什么?看到这个线程了吗?