Program Tip

JQuery.ajax 성공 데이터에서 JSON 구문 분석

programtip 2020. 10. 28. 20:33
반응형

JQuery.ajax 성공 데이터에서 JSON 구문 분석


JQery.ajax 호출에서 JSON 개체의 내용을 가져 오는 데 문제가 있습니다. 내 전화 :

$('#Search').click(function () {
    var query = $('#query').valueOf();
    $.ajax({
        url: '/Products/Search',
        type: "POST",
        data: query,
        dataType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
            for (var x = 0; x < data.length; x++) {
                content = data[x].Id;
                content += "<br>";
                content += data[x].Name;
                content += "<br>";
                $(content).appendTo("#ProductList");
               // updateListing(data[x]);
            }
        }
    });
});

"alert (data)"에 다음과 같은 내용이 표시되기 때문에 JSON 객체가 올바르게 반환되는 것 같습니다.

[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]

그러나 다음을 사용하여 페이지에 ID 또는 이름을 표시하려고 할 때 :

content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";

페이지에 "정의되지 않음"을 반환합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

도와 주셔서 감사합니다.


데이터는 JSON의 문자열 표현으로 다시 돌아오고 있으며 JavaScript 개체로 다시 변환하지 않습니다. (가) 설정 dataType만 할 수 'json'는 자동으로 변환하도록.


다음을 사용하는 것이 좋습니다.

var returnedData = JSON.parse(response);

JSON 문자열 (텍스트 일 ​​경우)을 JavaScript 개체로 변환합니다.


이러한 유형의 실수 (json 대신 문자열 사용)가 발생하지 않도록 할 수있는 방법 중 하나는 alert. 당신이 할 때

alert(data)

데이터가 문자열이면 포함 된 모든 것을 인쇄합니다. 그러나 인쇄하면 json 객체입니다. 경고에서 다음과 같은 응답을 받게됩니다.

[object Object]

이것이 응답이라면 이것을 객체 (이 경우 json)로 사용할 수 있음을 확신 할 수 있습니다.

따라서 다음을 수행하여 사용하기 전에 먼저 문자열을 json으로 변환해야합니다.

JSON.parse(data)

잘 작동합니다. 예 :

.ajax({

            url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
            type: 'GET',
            cache: false,
            success: function (result) {

                //  alert(jQuery.dataType);
                if (result) {
                    //  var dd = JSON.parse(result);
                    alert(result[0].Id)
                }

            },
            error: function () {
                alert("No");
            }
        });

마지막으로이 문장을 사용해야합니다 ...

result[0].Whatever

글쎄 ... 당신은 거기에 약 3/4 정도입니다 ... 당신은 이미 JSON을 텍스트로 가지고 있습니다.

문제는이 문자열이 전송 된 필드와 관련된 속성이있는 JavaScript 객체 인 것처럼 처리하는 것처럼 보인다는 것입니다.

그건 ... 그냥 문자열이 아닙니다.

"content = data [x] .Id;"와 같은 쿼리 JavaScript가보고있는 문자열에 연결된 이러한 속성을 찾지 못하기 때문에 실패 할 수 있습니다. 다시 말하지만, 그냥 문자열입니다.

JSON 개체의 구문 분석 방법을 통해 데이터를 JSON으로 간단히 구문 분석 할 수 있어야합니다.

myResult = JSON.parse(request.responseText);

이제 myResult는 AJAX를 통해 전송 된 속성을 포함하는 자바 스크립트 객체입니다.

그렇게하면하려는 것처럼 보이는 방식으로 처리 할 수 ​​있습니다.

ECMA5가 추가 될 때 JSON.parse가 추가 된 것처럼 보이므로 상당히 현대적인 모든 것이 기본적으로 처리 할 수 ​​있어야합니다. 화석을 처리해야하는 경우 jQuery 또는 JSON2 와 같은 외부 라이브러리를 사용 해도 됩니다.

공식적으로,이 이미 다른 사람을 위해 앤디 E 응답했다 여기 .

편집 - '공식 또는 신뢰할 수있는 소스'에 대한 요청을 보았고 아마도 가장 신뢰할 수있는 코더 중 하나는 John Resig ~ ECMA5 JSON 일 것입니다 ~ 네이티브 JSON 지원과 관련하여 실제 ECMA5 사양에 연결했을 것입니다. 건식 사양보다는 Resig와 같은 마스터를 참조하십시오.


eachjson 객체를 살펴 보려면 jquery 함수를 사용해보십시오 .

$.each(data,function(i,j){
    content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
    $('#ProductList').append(content);
});

jQuery parseJSON 메서드를 사용할 수 있습니다.

var Data = $.parseJSON(response);

입력 유형 버튼

 <input type="button" Id="update" value="Update">

Perl에서 AJAX로 양식을 성공적으로 게시했습니다. 양식을 게시 한 후 컨트롤러는 아래와 같이 JSON 응답을 반환합니다.

$(function(){ 

$('#Search').click(function() {
var query = $('#query').val();
var update    = $('#update').val();

     $.ajax({
                type: 'POST',
                url:'/Products/Search/',
                data:{
                    'insert'   :update,
                    'query'  :address,
                    },
                success: function(res){
                $('#ProductList').empty('');
                console.log(res);
                json=JSON.parse(res);
                for(var i in json){
                var row=$('<tr>');
                row.append($('<td id='+json[i].Id+'>').html(json[i].Id));
                row.append($('<td id='+json[i].Name+'>').html(json[i].Name));
                $('</tr>');
                $('#ProductList').append(row);    
                }
              },
                error: function() {
                alert("did not work");
                location.reload(true);
                }
        });
     });
});

From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).

Or you can set the dataType to json to convert it automatically.


I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this

$.ajax({
    url : url,
    dataType : 'json'
})
.done(function(data, statusText, resObject) {
   var jsonData = resObject.responseJSON
})

parse and convert it to js object that's it.

success:function(response){
        var content="";
        var jsondata= JSON.parse(response);
        for(var x=0;x<jsonData.length;x++){
            content += jsondata[x].Id;
            content += "<br>";
            content += jsondata[x].Name;
            content += "<br>";
        }   
        $("#ProductList").append(content);  
    }

참고URL : https://stackoverflow.com/questions/5289078/parse-json-from-jquery-ajax-success-data

반응형