jQuery AJAX使用返回值上传到ASMX WebMethod

时间:2018-12-04 11:44:58

标签: javascript jquery asmx webmethod

我正在努力使它正常工作。如果我包含dataType:“ json”,我总是被抛出到request.fail,但实际上没有错误显示在浏览器控制台中。如果删除dataType:“ json”,则无法获得返回响应:控制台中出现错误:未捕获的TypeError:无法读取未定义的属性'Guid'。

其他所有功能都可以正常工作-文件可以上传并写入数据库。

jQuery:

$( document ).on( "change", "input[name='files']", function( e ) {

    var files = $( this ).prop( "files");
    var data = new FormData();

    var request;
    var result;
    var modal = $( this ).closest( ".modal" );
    var itemid = modal.data( "itemid" );

    for( var i = 0; i < files.length; i++ ) {

        data.append( "id", itemid );
        data.append( "file", files[i] );

        request = $.ajax( {

            type: "POST",
            url: "/webservices/webservices.asmx/UploadFile",
            data: data,
            // dataType: "json",
            contentType: false,
            processData: false

        } );

        request.done( function( response ) {

            result = response.d;
            console.log( result.Guid );

        } );

        request.fail( function( response ) {

            console.log( response.responseText );

        } );

        request.always( function() {

            data.delete( itemid );
            data.delete( files[i] );

        } );

    }

} );

WebMethod(出于论坛目的而简化):

public class Response
{

    public Guid Guid;
    public bool Toggle;
    public string Date;
    public string Text;
    public string Image;

}

[WebMethod]
public Response UploadFile()
{

    Response Response = new Response();

    Response.Guid = BasePage.NewGuid;
    Response.Text = "Hello, world!";
    Response.Image = "/images/test.png";
    return Response;

}

控制台(request.done-无dataType):

Uncaught TypeError: Cannot read property 'Text' of undefined
    at Object.<anonymous> (eandf.js:218)
    at j (jquery-latest.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-latest.min.js:2)
    at x (jquery-latest.min.js:4)
    at XMLHttpRequest.b (jquery-latest.min.js:4)

控制台(request.fail-数据类型:json):

<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="<stripped out>">
    <Guid>53dc43ef-0fe5-4aaf-9866-06d23e3161d2</Guid>
    <Toggle>false</Toggle>
    <Text>Hello, world!</Text>
    <Image>/images/test.png</Image>
</Response>

1 个答案:

答案 0 :(得分:0)

尝试使用此代码

 request = $.ajax( {

            type: "POST",
            url: "/webservices/webservices.asmx/UploadFile",
            data: data,
            dataType: "json",
            processData: false,
            cache:false

        } );

var response = JSON.parse(request.responseText);

//// Use above variable to get the response data

让我知道是否有帮助