ajax提交問題

CI框架中使用ajax提交,開始沒有加 contentType ,打印頁面報錯:javascript

   XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, abort: function, onreadystatechange: function…}
        parsererror
        Invalid JSON: Disallowed Key Characters.
php

添加contentType:"application/json; charset=utf-8",報錯消失,後臺能收到發送的數據;html

 代碼以下:java

 

html代碼:ajax

<input  id = 'test' type ="button"   value="提交">json

js代碼:segmentfault

<script type="text/javascript"> 數組

$('#test').click(function(){ app

         var json = {
            'sensor_name':123,
            'alarm':45
        };框架

      alert(JSON.stringify(json));

       //注意這裏是單引號仍是雙引號,後臺PHP json_decode 轉義的時候裏面是雙引號,因此再拼 變量 json 的時候,裏面要使用單引號這樣JSON.stringify(json)纔會變成雙引號;

        $.ajax({   

             url:"<?php echo base_url();?>index.php/alarm_manage/alarm_manage/set_alarm_info",    

             type:"post",   

             //contentType:"application/json; charset=utf-8",    

            dataType:"json",   

            data:{data:JSON.stringify(json)}, 

            error:function(XMLHttpRequest,textStatus,errorThrown){      

                  console.log(XMLHttpRequest);      

                  console.log(textStatus);      

                  console.log(errorThrown);

            },   

            success:function(msg){

                 console.log(msg);   

            }   

       });      

})

</script>

 

後臺PHP代碼(對象轉數組過程當中,注意單引號和雙引號;)

    public function set_alarm_info(){

        $data = json_decode($_POST['data'],ture);

        echo $data['sensor_name'];

   }

 

 

參考:

https://segmentfault.com/q/1010000005329558?sort=created

相關文章
相關標籤/搜索