Jquery - Uncarched TypeError: 'in' 연산자를 사용하여 다음 위치에서 '324'를 검색할 수 없습니다.
get request를 ajax로 전송하고 서버에서 반환된 json 데이터를 html로 출력하려고 합니다.
그런데 이 에러가 났어요.
Uncaught TypeError: Cannot use 'in' operator to search for '324' in
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]
이것은 ajax를 통해 php 파일로 Get 요청을 보내는 내 코드입니다.$.를 사용했을 때 위와 같은 오류가 발생합니다.
parentCat.on('change', function(e){
parentCatId = $(this).val();
$.get(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
}
)
})
쿼리 결과를 json 형식으로 반환하는 제 PHP 코드입니다.
public function actionAjax(){
$parentCatId=$_GET['parentCatId'];
$catData = Category::getTargetCategoryData($parentCatId);
echo CJSON::encode($catData);
Yii::app()->end();
}
이 php가 출력하는 json 데이터는 다음과 같습니다.
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]
이 문제를 어떻게 해결할 수 있을까요?
오브젝트가 아닌 JSON 문자열이 있습니다.jQuery에게 JSON 응답을 기대하면 해석할 수 있다고 말합니다.$.getJ 사용$.get 대신 SON 또는 dataType 인수를 전달합니다.$.get:
$.get(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
},
'json'
);
를 사용할 수도 있습니다.$.parseJSON(data)PHP 스크립트에서 가져온 문자열을 실제 JSON 배열로 명시적으로 변환합니다.
JSON을 가져오는 경우 $.getJSON()을 사용하여 자동으로 JSON을 JS 개체로 변환합니다.
다음과 같이 json data Type을 추가하여 유사한 오류를 수정했습니다.
$.ajax({
type: "POST",
url: "someUrl",
dataType: "json",
data: {
varname1 : "varvalue1",
varname2 : "varvalue2"
},
success: function (data) {
$.each(data, function (varname, varvalue){
...
});
}
});
컨트롤러에서는 다음과 같은 문자열 주위에 큰따옴표를 사용해야 했습니다(주의: Java로 이스케이프해야 합니다).
@RequestMapping(value = "/someUrl", method=RequestMethod.POST)
@ResponseBody
public String getJsonData(@RequestBody String parameters) {
// parameters = varname1=varvalue1&varname2=varvalue2
String exampleData = "{\"somename1\":\"somevalue1\",\"somename2\":\"somevalue2\"}";
return exampleData;
}
따라서 숫자가 문자열로 사용되는 경우 숫자 주위에 큰따옴표를 사용해 볼 수 있습니다(마지막 쉼표를 삭제합니다.
[{"id":"50","name":"SEO"},{"id":"22","name":"LPO"}]
getJ 사용아들.
$.getJSON(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
});
자세한 것은 이쪽 http://api.jquery.com/jQuery.getJSON/을 참조해 주세요.
내 경우 유형 컨트롤러에 응답이 JSON 개체임을 알리는 것을 잊었습니다.
response.setContentType("application/json");
언급URL : https://stackoverflow.com/questions/18502101/jquery-uncaught-typeerror-cannot-use-in-operator-to-search-for-324-in
'programing' 카테고리의 다른 글
| $http가 요청으로 쿠키를 보내지 않음 (0) | 2023.03.16 |
|---|---|
| Spring Security anonymous 403 대신 401 (0) | 2023.03.16 |
| 중첩된 JSON: 개체에 새 항목을 추가하는 방법(푸시) (0) | 2023.03.16 |
| React를 사용하여 구성 파일을 저장하고 읽는 방법 (0) | 2023.03.16 |
| 정의되지 않은 gulp의 속성 'sublic'을 읽을 수 없습니다. (0) | 2023.03.16 |