jQuery/JavaScript를 사용하여 JSON 데이터를 해석하는 방법
다음과 같은 JSON을 반환하는 AJAX 콜이 있습니다.
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
success: function (data) {
var names = data
$('#cand').html(data);
}
});
});
내부#canddiv 내가 얻을 것:
[ { "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" } ]
어떻게 하면 이 데이터를 루프해서 각각의 이름을 div에 넣을 수 있을까요?
서버측 스크립트가 올바르게 설정되어 있지 않은 경우Content-Type: application/json응답 헤더를 사용하여 jQuery에 이것이 JSON임을 나타내야 합니다.dataType: 'json'파라미터를 지정합니다.
그런 다음 함수를 사용하여 데이터를 루프할 수 있습니다.
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});
또는 를 사용합니다.$.getJSON방법:
$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
설정dataType:'json'는 JSON을 해석합니다.
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: {get_param: 'value'},
dataType: 'json',
success: function (data) {
var names = data
$('#cand').html(data);
}
});
또는 다음을 사용할 수 있습니다.
var parsedJson = $.parseJSON(jsonToBeParsed);
그런 다음 다음 작업을 반복할 수 있습니다.
var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';
...을 사용하여$().each:
var json = $.parseJSON(j);
$(json).each(function (i, val) {
$.each(val, function (k, v) {
console.log(k + " : " + v);
});
});
다음 코드를 사용해 보십시오. 내 프로젝트에서 작동합니다.
//start ajax request
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
for (var i=0;i<json.length;++i)
{
$('#results').append('<div class="name">'+json[i].name+'</>');
}
}
});
$(document).ready(function () {
$.ajax({
url: '/functions.php',
type: 'GET',
data: { get_param: 'value' },
success: function (data) {
for (var i=0;i<data.length;++i)
{
$('#cand').append('<div class="name">data[i].name</>');
}
}
});
});
그 코드를 사용하세요.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Your URL",
data: "{}",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
ok 나도 같은 문제가 있어서 제거함으로써 이렇게 고칩니다.[]부터[{"key":"value"}]:
- php 파일에서 이렇게 출력합니다.
echo json_encode(array_shift($your_variable));
- 성공 함수로 다음과 같이 하십시오.
success: function (data) {
var result = $.parseJSON(data);
('.yourclass').append(result['your_key1']);
('.yourclass').append(result['your_key2']);
..
}
루프를 할 수도 있습니다.
위의 모든 솔루션에 동의합니다만, 이 문제의 근본 원인을 지적하기 위해서는 위의 모든 코드에서 주요 역할 담당자는 다음과 같습니다.
dataType:'json'
이 행을 놓치면(선택사항), 서버에서 반환되는 데이터는 전체 길이 문자열(기본 반환 유형)로 처리됩니다.이 코드 행을 추가하면 jQuery가 가능한json 문자열을 json 객체로 변환하도록 지시됩니다.
json data object가 예상되는 경우 jQuery ajax 호출에서는 이 행을 지정해야 합니다.
var jsonP = "person" : [ { "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" } ];
var cand = document.getElementById("cand");
var json_arr = [];
$.each(jsonP.person,function(key,value){
json_arr.push(key+' . '+value.name + '<br>');
cand.innerHTML = json_arr;
});
<div id="cand">
</div>
Json 데이터
data = {"clo":[{"fin":"auto"},{"fin":"robot"},{"fin":"fail"}]}
취득시
$.ajax({
//type
//url
//data
dataType:'json'
}).done(function( data ) {
var i = data.clo.length; while(i--){
$('#el').append('<p>'+data.clo[i].fin+'</>');
}
});
JavaScript에서 이 작업을 수행하는 방법은 다음과 같습니다. 이 방법은 다음과 같습니다.
let data = '{ "name": "mark"}'
let object = JSON.parse(data);
console.log(object.name);
이것은 마크를 인쇄할 것이다.
$.ajax({
url: '//.xml',
dataType: 'xml',
success: onTrue,
error: function (err) {
console.error('Error: ', err);
}
});
$('a').each(function () {
$(this).click(function (e) {
var l = e.target.text;
//array.sort(sorteerOp(l));
//functionToAdaptHtml();
});
});
언급URL : https://stackoverflow.com/questions/8951810/how-to-parse-json-data-with-jquery-javascript
'programing' 카테고리의 다른 글
| angularjs $log - 행 번호 표시 (0) | 2023.03.23 |
|---|---|
| 각도 재료 설계 - 화면 크기에 따라 플렉스 값 변경 (0) | 2023.03.23 |
| CoffeeScript - 각도 식에서 DOM 노드를 참조할 수 없습니다. (0) | 2023.03.23 |
| 스프링 부트에서의 json 날짜 형식 (0) | 2023.03.23 |
| 워드프레스:서버에서 로컬 호스트로 다중 사이트 이동 (0) | 2023.03.18 |