IT

jQuery ajax 호출에 여러 매개 변수 전달

lottoking 2020. 8. 25. 08:22
반응형

jQuery ajax 호출에 여러 매개 변수 전달


aspx 페이지에서 웹 메소드를 호출하는 다음 jquery 코드가 있습니다.

$.ajax({
    type: "POST",
    url: "popup.aspx/GetJewellerAssets",
    contentType: "application/json; charset=utf-8",
    data: '{"jewellerId":' + filter + '}',
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed
});

여기에 웹 메소드 서명이 있습니다.

[WebMethod]
public static string GetJewellerAssets(int jewellerId)
{

이것은 잘 작동합니다.

하지만 이제 웹 메서드에 두 개의 매개 변수를 전달해야합니다.

새로운 웹 메소드는 다음과 가변합니다.

[WebMethod]
public static string GetJewellerAssets(int jewellerId, string locale)
{
}

이 새 메서드를 호출하기 위해 클라이언트 코드를 어떻게 변경하고 서명합니까?

편집하다 :

다음 두 가지 구문이 작동했습니다.

data: '{ "jewellerId":' + filter + ', "locale":"en" }',

data: JSON.stringify({ jewellerId: filter, locale: locale }),

필터와 로케일은 지역 변수입니다.


매개 변수를 전달하기 위해 사용하지 않는 데이터를 사용하십시오.

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: { jewellerId: filter, locale: 'en-US' },
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});

최신 정보 :

주석 섹션에서 @Alex가 제안한대로 ASP.NET PageMethod는 매개 변수가 요청에서 JSON으로 인코딩 될 예상되는 제안 JSON.stringify데이터 해시에 적용해야합니다.

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ jewellerId: filter, locale: 'en-US' }),
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});


data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}',

데이터 개체에 필요한만큼 속성을 추가하기 만하면됩니다.

 $.ajax({
                    type: "POST",
                    url: "popup.aspx/GetJewellerAssets",
                    contentType: "application/json; charset=utf-8",
                    data: {jewellerId: filter , foo: "bar", other: "otherValue"},
                    dataType: "json",
                    success: AjaxSucceeded,
                    error: AjaxFailed
                });

David Hedlund를 제외한 모든 답변에서 json 문자열 / 객체가 유효하지 않다는 것을 다른 사람이 발견 했습니까? :)

JSON 개체는 { "key": ( "value"| 0 | false)} 형식으로 지정해야합니다. 또한 문자열로 작성하는 것은 객체를 문자열 화하는 것보다 훨씬 적게 필요합니다.


$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',      
    data: "jewellerId=" + filter+ "&locale=" +  locale,  
    success: AjaxSucceeded,
    error: AjaxFailed
});

아래 방법을 사용하여 ajax 호출을 사용하여 데이터를 보내지 마십시오.

data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}'

실수로 사용자가 작은 따옴표 또는 큰 따옴표와 같은 특수 문자를 입력하면 잘못된 문자열로 인해 ajax 호출이 실패합니다.

아래 방법을 사용하여 문제없이 웹 서비스를 호출하십시오.

var parameter = {
       jewellerId: filter,
       locale : locale 
};


data: JSON.stringify(parameter)

위의 매개 변수는 자바 스크립트 객체의 이름이며이를 ajax 호출의 데이터 속성에 전달할 때 문자열 화합니다.


[이 줄은 Asp.net에서 완벽하게 작동하며 jason에서 웹 제어 필드를 찾습니다. 예 : <% Fieldname %>]

 data: "{LocationName:'" + document.getElementById('<%=txtLocationName.ClientID%>').value + "',AreaID:'" + document.getElementById('<%=DropDownArea.ClientID%>').value + "'}",

    var valueOfTextBox=$("#result").val();
    var valueOfSelectedCheckbox=$("#radio:checked").val();

    $.ajax({
    url: 'result.php',
    type: 'POST',
    data: { forValue: valueOfTextBox, check : valueOfSelectedCheckbox } ,
    beforeSend: function() {

          $("#loader").show();
       },
    success: function (response) {
       $("#loader").hide();
       $("#answer").text(response);
    },
    error: function () {
        //$("#loader").show();
        alert("error occured");
    }
    }); 

전달하는 데이터에 관한 모든 것; 올바른 형식의 문자열이어야합니다. 빈 데이터를 전달하는 경우 데이터 : {}이 작동합니다. 그러나 여러 매개 변수를 사용하려면 적절한 형식을 지정해야합니다.

var dataParam = '{' + '"data1Variable": "' + data1Value+ '", "data2Variable": "' + data2Value+ '"' +  '}';

....

데이터 : dataParam

...

이해하는 가장 좋은 방법은 자세한 오류를 알 수 있도록 적절한 메시지 매개 변수가있는 오류 처리기를 사용하는 것입니다.


json을 사용하여 여러 매개 변수를 성공적으로 전달했습니다.

data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",

참고 URL : https://stackoverflow.com/questions/1916309/pass-multiple-parameters-to-jquery-ajax-call

반응형