$ ajax POST에서 매개 변수를 전달하는 방법은 무엇입니까?
이 링크에 명시된대로 튜토리얼을 따랐습니다 . 어떤 이유로 든 아래 코드에서 데이터가 매개 변수로 URL에 추가되지 않지만 사용하여 URL에 직접 설정 /?field1="hello"
하면 작동합니다.
$.ajax({
url: 'superman',
type: 'POST',
data: { field1: "hello", field2 : "hello2"} ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
간단한 경우에 jQuery의 구문 $.post
또는 $.get
구문을 사용하는 것이 좋습니다 .
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
});
실패 사례를 포착해야하는 경우 다음을 수행하십시오.
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
또한 항상 JSON 문자열을 보내면 맨 끝에 하나 이상의 매개 변수와 함께 $ .getJSON 또는 $ .post를 사용할 수 있습니다 .
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}, 'json');
GET 방법을 사용해보십시오.
var request = $.ajax({
url: 'url',
type: 'GET',
data: { field1: "hello", field2 : "hello2"} ,
contentType: 'application/json; charset=utf-8'
});
request.done(function(data) {
// your success code here
});
request.fail(function(jqXHR, textStatus) {
// your failure code here
});
POST 메소드가있는 URL에서 매개 변수를 볼 수 없습니다.
편집하다:
지원 중단 공지 : jqXHR.success (), jqXHR.error () 및 jqXHR.complete () 콜백은 jQuery 3.0부터 제거되었습니다. 대신 jqXHR.done (), jqXHR.fail () 및 jqXHR.always ()를 사용할 수 있습니다.
Jquery.ajax 는 POST 데이터를 GET 데이터에 대해 자동으로 인코딩하지 않습니다. Jquery는 데이터가 요청 본문에 추가되어 유선을 통해 직접 전송되도록 사전 형식화 될 것으로 예상합니다.
해결책은 jQuery.param 함수 를 사용하여 POST 요청을 처리하는 대부분의 스크립트가 예상하는 쿼리 문자열을 작성하는 것입니다.
$.ajax({
url: 'superman',
type: 'POST',
data: jQuery.param({ field1: "hello", field2 : "hello2"}) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
이 경우 param
메소드는 데이터를 다음과 같이 형식화합니다.
field1=hello&field2=hello2
The Jquery.ajax documentation says that there is a flag called processData
that controls whether this encoding is done automatically or not. The documentation says that it defaults to true
, but that is not the behavior I observe when POST
is used.
function FillData() {
var param = $("#<%= TextBox1.ClientID %>").val();
$("#tbDetails").append("<img src='Images/loading.gif'/>");
$.ajax({
type: "POST",/*method type*/
contentType: "application/json; charset=utf-8",
url: "Default.aspx/BindDatatable",/*Target function that will be return result*/
data: '{"data":"' + param + '"}',/*parameter pass data is parameter name param is value */
dataType: "json",
success: function(data) {
alert("Success");
}
},
error: function(result) {
alert("Error");
}
});
}
In a POST request, the parameters are sent in the body of the request, that's why you don't see them in the URL.
If you want to see them, change
type: 'POST',
to
type: 'GET',
Note that browsers have development tools which lets you see the complete requests that your code issues. In Chrome, it's in the "Network" panel.
You can do it using $.ajax or $.post
Using $.ajax :
$.ajax({
type: 'post',
url: 'superman',
data: {
'field1': 'hello',
'field2': 'hello1'
},
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
Using $.post :
$.post('superman',
{
'field1': 'hello',
'field2': 'hello1'
},
function (response, status) {
alert(response.status);
}
);
$.ajax(
{
type: 'post',
url: 'superman',
data: {
"field1": "hello",
"field2": "hello1"
},
success: function (response) {
alert("Success !!");
},
error: function () {
alert("Error !!");
}
}
);
type: 'POST'
, will append **parameters to the body of the request** which is not seen in the URL while type: 'GET'
, appends parameters to the URL which is visible.
Most of the popular web browsers contain network panels which displays the complete request.
In network panel select XHR to see requests.
This can also be done via this.
$.post('superman',
{
'field1': 'hello',
'field2': 'hello1'
},
function (response) {
alert("Success !");
}
);
Your code was right except you are not passing the JSON keys as strings.
It should have double or single quotes around it
{ "field1": "hello", "field2" : "hello2"}
$.ajax(
{
type: 'post',
url: 'superman',
data: {
"field1": "hello", // Quotes were missing
"field2": "hello1" // Here also
},
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
}
);
For send parameters in url in POST
method You can simply append it to url like this:
$.ajax({
type: 'POST',
url: 'superman?' + jQuery.param({ f1: "hello1", f2 : "hello2"}),
// ...
});
참고URL : https://stackoverflow.com/questions/18697034/how-to-pass-parameters-in-ajax-post
'IT story' 카테고리의 다른 글
모든 Ruby 테스트 제기 : nil : NilClass에 대해 정의되지 않은 메소드 'authenticate' (0) | 2020.07.01 |
---|---|
web.xml에서 기본 오류 페이지를 지정하는 방법은 무엇입니까? (0) | 2020.07.01 |
파이썬을 사용하여 curl 명령을 실행하는 방법 (0) | 2020.07.01 |
원점 / HEAD는 어떻게 설정됩니까? (0) | 2020.07.01 |
자바 스크립트 : 부정적인 lookbehind 동등? (0) | 2020.07.01 |