Jquery JSON转换

Jquery JSON转换,jquery,json,Jquery,Json,我获取数据,然后在服务器端将其序列化为JSON字符串,然后将其传递给客户端。 假设我在客户端获得的数据是JSON字符串,我如何通过JSON迭代在客户端创建HTML表?(已编辑。假设您的表有一个id=“myTable”,您可以按照迭代块中的描述追加您的项[id,Nombre]。 您没有指定如何接收数据,但假设在jquery ajax请求之后接收数据。这可能是一个如何迭代JSON的示例 首先,使用jQuery.parseJSON(response.responseText) 要在客户端执行的java

我获取数据,然后在服务器端将其序列化为JSON字符串,然后将其传递给客户端。 假设我在客户端获得的数据是JSON字符串,我如何通过JSON迭代在客户端创建HTML表?

(已编辑。假设您的表有一个id=“myTable”,您可以按照迭代块中的描述追加您的项[id,Nombre]。

您没有指定如何接收数据,但假设在jquery ajax请求之后接收数据。这可能是一个如何迭代JSON的示例

首先,使用
jQuery.parseJSON(response.responseText)

要在客户端执行的javascript块:

$.ajax({
  type: 'POST',
  url: $("#YourFormID").attr('action'),
  dataType: 'json',
  data: $("#YourFormID").serialize(),
  beforeSend: function(objeto) {
  },
  complete: function(response) {
  },
  success: function(response) {
    // Parse the JSON received
    jSONResp = jQuery.parseJSON(response.responseText);     
    // If your expected list is called 'myList'
    if ('myList' in jSONResp) {

        // If your <table> does not exists, you can create it at this time, within an existing element (someContainer):
        $("#someContainer").append('<table id="myTable"><tr><td>ID</td><td><td>Name</td></tr></table>');

        for (var i=0; i<jSONResp.myList.length; i++) {
            var item = jSONResp.myList[i];
            // Append a new <tr> with the current item data to the table
            $('#myTable').append('<tr><td>'+item["Id"]+'</td><td>'+item["Name"]+'</td></tr>');
        }
    }
  },
  error: function(objeto, quepaso, otroobj){
    alert("ERROR: "+quepaso);
  }
});
$.ajax({
键入:“POST”,
url:$(“#YourFormID”).attr('action'),
数据类型:“json”,
数据:$(“#YourFormID”).serialize(),
发送前:函数(objeto){
},
完成:功能(响应){
},
成功:功能(响应){
//解析接收到的JSON
jSONResp=jQuery.parseJSON(response.responseText);
//如果您期望的列表名为“myList”
if(jSONResp中的“myList”){
//如果不存在,则此时可以在现有元素(someContainer)中创建它:
$(“#someContainer”).append('IDName');

对于(var i=0;i到目前为止,您尝试过哪些代码?有很多教程可以做这件事。问题的范围太广了。如果您有特定的代码问题,请显示该代码并用适当的问题描述更新问题。我尝试过使用json.parse,但它给出了语法错误假设我以这种格式获取数据:varjsonString=[{“Id”:“10”,“Name”:“aaaaaa”},{“Id”:“1”,“Name”:“nnnn”}];如何迭代此值以在html表中转换?
数据:$(“#YourFormID”).serialize(),
-如果未正确设置内容类型请求头,请不要这样做。
jSONResp=jQuery.parseJSON(response.responseText)
-这不起作用。
响应
将是响应的文本,或者是解析响应时创建的JS数据结构,就像它是JSON一样(取决于内容类型响应标题所说的数据类型)。对,(编辑)我添加了更多内容,包括可能的带有内容类型的服务器响应。我在我们的一些项目中编写了这些脚本,它们可以工作。
jSONResp=jQuery.parseJSON(response.responseText);
仍然不能工作,因为
responseText
不太可能定义或包含JSON(除非您计划对JSON进行编码,然后在将该数组编码为JSON之前将其放在一个数组中(其中您有/**无论您正在序列化什么,项目数组等等**/),这将是很奇怪的。
<?PHP
$data = /** whatever you're serializing, array of items etc **/;
header('Content-Type: application/json');
echo json_encode($data);