passing multiple parameters to .asmx from jquery ajax GET

前端 未结 3 1417
猫巷女王i
猫巷女王i 2021-02-20 18:09

html

fill in names and check it out

Enter First Name

相关标签:
3条回答
  • 2021-02-20 18:42

    I hope that you use [ScriptMethod(ResponseFormat=ResponseFormat.Json)] attribute for the web method or set the same information in the web.config in case of the usage .NET 4.0.

    It seems to me that your first attempt was almost correct, but you should replace

    data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":' +
                        $('#myLastName').val() + '"}',
    

    to the

    data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":"' +
                        $('#myLastName').val() + '"}',
    

    (the starting double-quote was skipped before the $('#myLastName').val()).

    I strictly recommend you don't use manual serialization to JSON. For example if the text from $('#myFirstName').val() or $('#myLastName').val() will have '"' or '\' characters, that the characters must be escaped with additional backslash ('\') (see here). Instead of manual serialization you should use JSON.stringify function from the script json2.js which you can download from the http://www.json.org/js.html or here. In recent web browsers the function are native implemented and json2.js use the native implementation if it take place.

    The data parameter of $.ajax could be rewritten as the following:

    data: {
        firstName: JSON.stringify($('myFirstName').val()),
        lastName: JSON.stringify($('myLastName').val())
    }
    

    or in some situation even as

    data: {
        firstName: function() { return JSON.stringify($('myFirstName').val()); },
        lastName: function() { return JSON.stringify($('myLastName').val()); }
    }
    

    For more information see this old answer and probably also this.

    UPDATED: Sorry the correct version without the usage JSON.stringify could be without the data usage:

    url: 'UtilitieService.asmx/TestGetParametersDynamic?firstName=' +
         encodeURIComponent('"' + $('#myFirstName').val() + '"') +
         '&lastName=' + encodeURIComponent('"' + $('#myLastName').val() + '"')
    

    I strictly recommend you to use always only the JSON.stringify version which I described above.

    0 讨论(0)
  • 2021-02-20 18:51

    Pass multiple parameters using json

    data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + 
                           "'," + "'tempdata':'" +"myvalue" + "'}",
    
    0 讨论(0)
  • 2021-02-20 19:01
    • Your first attempt is passing the paramaters as a json string.
    • Your second attempt is missing = signs.

    You can pass a object to data, and jQuery will serialize it properly.

    $.ajax(
            {
                post: 'GET',
                data: {
                    firstName: $('myFirstName').val(),
                    lastName: $('myLastName').val()
                },
    ...
    
    0 讨论(0)
提交回复
热议问题