jQuery.ajax가 400개의 잘못된 요청을 반환합니다.
이것은 잘 작동합니다.
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
이것은 400개의 잘못된 요청을 반환합니다(오류 처리를 지원하기 위해 .ajax를 사용하여 위의 jQuery를 재구성한 것입니다).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
2가지 옵션만 더 추가하시면 될 것 같습니다(contentType그리고.dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Ajax 호출에 추가합니다.
contentType: "application/json; charset=utf-8",
dataType: "json"
답변이 늦었지만, 저는 이것을 업데이트할 가치가 있다고 생각했습니다.업데이트된 jQuery API 및 .success/.error가 더 이상 사용되지 않는 메서드를 반영하여 Andrea Turri 답변을 확장합니다.
jQuery 1.8.* 기준으로 이 작업을 수행하는 방법은 .done() 및 .fail()을 사용하는 것이 좋습니다.Jquery Docs
예.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
예를 들어 $.ajax 호출과 함께 'get' 또는 'post'를 일관되게 사용해야 합니다.
$.ajax({
type: 'get',
을 충족시켜야 합니다.
app.get{}/, 함수(req, res) {
그리고 우편으로
$.ajax({ type: 'post',
을 충족시켜야 합니다.
app.post('/', function(req, res) {
다음을 설정한 후에도 400 Bad Request 오류가 발생했습니다.
contentType: "application/json",
dataType: "json"
문제는 json 개체에 전달된 속성 유형에 있습니다.data속성이 Ajax 요청 개체에 있습니다.
문제를 파악하기 위해 오류 처리기를 추가한 다음 오류를 콘솔에 기록했습니다.속성에 대한 유효성 검사 오류가 있는 경우 콘솔 로그에 명확하게 표시됩니다.
이것이 제 초기 코드였습니다.
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
이제 요청을 한 후 브라우저 개발 도구에서 콘솔 탭을 확인했습니다.
다음과 같이 보였습니다.
responseJSON.errors[0]유효성 검사 오류가 분명하게 표시됩니다.JSON 값을 시스템으로 변환할 수 없습니다.끈. 경로: $.TestId. 즉, 변환해야 합니다.TestId요청하기 전에 데이터 개체의 문자열로 이동합니다.
아래와 같이 데이터 개체 생성을 변경하여 문제를 해결했습니다.
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
오류 개체를 기록하고 검사하여 다른 가능한 오류도 확인할 수 있을 것으로 생각합니다.
당신의.AJAX다음 두 가지로 통화가 완료되지 않았습니다.params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType전송하는 데이터 유형입니다.dataType당신이 서버로부터 기대하는 것은 무엇입니까?
추가로 사용해 보십시오.JSON.stringify()방법.그것은 회전할 때 사용됩니다.javascript에 반대하는.json현을 매다
언급URL : https://stackoverflow.com/questions/4156991/jquery-ajax-returns-400-bad-request
'codememo' 카테고리의 다른 글
| Swift UIV뷰 배경색 불투명도 (0) | 2023.08.26 |
|---|---|
| Spring Rest Controller에서 Excel 파일을 다운로드하는 방법 (0) | 2023.08.26 |
| 크롬/j쿼리 탐지되지 않은 범위 오류: 최대 호출 스택 크기를 초과했습니다. (0) | 2023.08.21 |
| 앵커 태그가 아무것도 참조하지 않도록 만드는 방법은 무엇입니까? (0) | 2023.08.21 |
| mariadb에서 자동 커밋을 해제하는 방법은 무엇입니까? (0) | 2023.08.21 |