简体   繁体   中英

Ajax undefined error when calling ASMX

<html>
<script src="json.js";/>
<script src = "jquery.js"/>
<script type="text/javascript">
    function PopulateBlendSpecification() {


    var data = new Object();
    data.Message = "message";
    alert(JSON.stringify(data));
    $.ajax({
        url: "Test.aspx/Test",
        type: "POST",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        data: JSON.stringify(data),
        success: function (result) {
            var listItems = [];
            var blendSpecItems = JSON.parse(result.d);

            for (var key in blendSpecItems) {
                listItems.push('<option value="' + blendSpecItems[key].BlendSpecID + '">' + blendSpecItems[key].BlendName
                            + '</option>');
            }

            var lBox = $('select[id$=lbBlendSpecs]');
            $(lBox).append(listItems.join(''));
        }
    })
}

Test.aspx.cs

      [WebMethod()]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public  static string  Test(string message)
    {
       return message;
    }

This works fine when I try this within one project. However, when I move the webmethod into a separate prjoject within the same solution I get an ajax error:

Error in: http://localhost/Test/MyWebService/Test.asmx/Test
 error: undefined
 type: ajaxError
 readystate: 4
 status: 500

Webmethod is case sensitive.In your code function is public static string Test(string message) in parameter message is in small letter and you have to pass data.Message M is capital so method is unable to find function in code side.

So if you change code like below your code will work fine

    [WebMethod()]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string Test(string Message)
    {
        return Message;
    }

when I move the webmethod into a separate prjoect within the same solution

Did you move it into a web service project and trying to consume in a web project, if that's the case this error would happen due to Cross site scripting restrictions. If you still need to have them in separate project, you will have to use jsonp and return jsonp friendly response.

You can find more info about JSONP + ASMX @ JSONP & ASMX Web Service .

您的asmx文件中是否有此标头[System.Web.Script.Services.ScriptService]。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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