请求响应不起作用

时间:2014-05-20 21:09:31

标签: php jquery ajax json post

这是我的 JSON 功能:

function createjson(){
  var json='{"jsondata":[[';
  $("#kup td").each(function(){
  if($(this).html()!="")
  {
    json+= parseInt($(this).html())+",";
    if($(this).index()%5==0 && $(this).index()!=0){
      json=json.substring(0,json.length-1);
      json+="],["
    }                       
  }             
 });
json=json.substring(0,json.length-3);
json+="]]}";
console.log(json); //-> works fine.
return json;
};

AJAX 部分:

$("#button").click(function(){
  $.ajax({
    type:"POST",
    url:"x.php",
    data: createjson(),
    contentType: "application/json",
dataType: "json",
    success: function(result) {
        alert("done"); //->works
    }
  });           
}); 

PHP 部分:

<?php
   header('Content-type: application/json');
   echo "<pre>";
   echo    $_POST['jsondata'];
   echo "</pre>";
?>

因此,“警报”有效,但在控制台中检查响应时,它只返回“<pre></pre>

任何解决方案?

1 个答案:

答案 0 :(得分:1)

  

data选项可以包含表单的查询字符串   key1 = value1&amp; key2 = value2,或{key1:'value1'形式的对象,   key2:'value2'}。如果使用后一种形式,则转换数据   在发送之前使用jQuery.param()将查询字符串转换为查询字符串。这个   通过将processData设置为false

可以规避处理

。来自jquery API doc

我没有对它进行过测试,但是应该给出强烈的改变结构的方法,试一试:

function createdata(){
  var data;
  $("#kup td").each(function(){
    if($(this).html()!="")
    {
      data.push( parseInt( $(this).html() ) );
      //...                    
    }             
  });
console.log(data);
return data;
};

$("#button").click(function(){
  var data = createdata();
  $.ajax({
    type:"POST",
    url:"x.php",
    data: {createjson:data},
    contentType: "application/json",
    dataType: "json",
    success: function(result) {
        alert("done"); //->works
    }
  });           
});