本帖最后由 teacher1998 于 2013-11-27 22:37:32 编辑

解决方案 »

  1.   

    当 contentType 为 application/x-www-form-urlencoded 时(默认值)
    才能用 $_POST 得到传入的数据
    而你的却是 application/json;charset=utf-8
    这并不是 php 所能识别的类型声明,不能替你解析。所以你只能用 php://input 取得,并用 parse_str 自行解析
    而形如 a=1&b=2&c=3 这样的数据,分明就不是 json 格式。即便 php 能识别 application/json 类型,也不能解析你这样的数据
      

  2.   

    LZ,你把  2个文件的contentType都去掉就可以了。
      

  3.   

    to : 玛特斯维尔定律, 你这个就变成plain text了,不是json。to: xuzuning 版主,那php怎么解析json格式的数据呢? 我这分明就是json数据啊。
      

  4.   

    用json_decode 转化为php可读取的值
      

  5.   

    我试过了,json_decode不行啊,
      

  6.   

    汗,这个怎么会不可以!你把你的json数据贴出个例子来
      

  7.   

    你的 $str = {"id":5, "cat":4, "price":3, "num": 2}; 是 js 对象
    s  = '{"id":"5", "cat":"4", "price":"3", "num":"2"}';
    才是可被 json_decode 解析的 json 数据$.ajax 会将 js 的对象转换成形如 id=5&cat=4&price=3&num=2 这样的字符串,称之为序列化(serialize)而形如 id=5&cat=4&price=3&num=2 这样的字符串,在web开发中称之为 uri参数串
    php 会自动将其转换到 $_POST 或 $_GET 数组中,当然前提是你传递了正确的类型声明
      

  8.   

    To: xuzuning 版主,多谢你的提点,差不多弄好了。多谢。后台我这样弄: header('Content-type: application/json');
    $data = json_decode(file_get_contents("php://input"), true);    $id = $data["id"]; 
        $cat = $data["cat"]; 
        $price = $data["price"]; 
        $num = $data["num"]; 

    echo $id." ".$cat." ".$price." ".$num;前台这样$("#submitBtn").click(function(){ //$str = {"id":5, "cat":4, "price":3, "num": 2}; 
    $str  = '{"id":"5", "cat":"4", "price":"3", "num":"2"}';
     
    $.ajax({
    type: 'POST',
    url: 'update.php',
    data: $str,
    dataType:'json',
    contentType:"application/json;charset=utf-8", 
    success: function(data) {
    $("#result").html(JSON.parse(data));
    },    
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
    $("#result").html("failed content: " + $str['id']+" " + $str['cat'] + " " + $str['price'] + " " + $str['num'] + "<br>failed reason: " + textStatus+" " + errorThrown + "<br/>" + XMLHttpRequest.responseText);

    //alert("error " + XMLHttpRequest.responseText);
    alert(JSON.parse(data));
    }       
    });
    });
    输出:
    failed content: undefined undefined undefined undefined
    failed reason: parsererror SyntaxError: Unexpected number
    5 4 3 2为什么还会报错呢?版主帮看看?这两天才弄php,小白之处见谅,谢谢。
      

  9.   

    错误是哪里出的?请给全错误信息看上去不像是 php 报的错你 js 部分 有 dataType:'json'
    表示要求将返回内容当做 json 解释
    而你在 php 中 echo $id." ".$cat." ".$price." ".$num;
    显然不是输出一个 json 数据