jquery的Ajax請求 返回的數據類型一定要一致json


<script src="__PUBLIC__/js/jquery-1.11.1.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){

 $.ajax(
    {
        type: 'get',
        url: 'http://ali.8g.com/index.php/Home/Ajax/Index',
        cache:false,
        dataType: 'json',
        data: {'src':'1323213',"uid": '546546'},
        async: false,
        beforeSend:function()
        {//觸發ajax請求開始時執行
            $("p").append("--馬上提交--");

        },                
        success: function (msg, textStatus) 
        {//有數據返回時
            alert(msg);
            if(msg.result==1)
            {
                $("p").append("--提交成功");
            }
            else
            {
               $("p").append("--提交成功--判斷");               
            }
        },
        error:function (textStatus) 
        {//網絡繁忙 錯誤
             
        },
        complete: function(msg, textStatus)
        { //ajax請求完成時執行  
                
            if(msg.result==1)
            {
               alert(msg);
 
            }
        }                
    });   




});
</script>

 

 

服務器:

<?php
namespace Home\Controller;
use Think\Controller;
class AjaxController extends Controller {
    public function index(){
        //$this->show('Ajax','utf-8');
        
        file_put_contents("test.txt","Hello World. Testing!");
        echo json_encode("123");
        exit;
    }

}

服務器一定是json 數據返回,整個過程才沒有錯誤

 

----------------------如果要解析對象數據的話--看下面

服務端

<?php
namespace Home\Controller;
use Think\Controller;
class AjaxController extends Controller {
    public function index(){
        //$this->show('Ajax','utf-8');
        $result = array(
                'result'=>'03211',
                'info'=>'info88'        
        );
        echo json_encode($result);
        exit;
    }

}

客戶端解析這個數組形式的json(跨域需要jsonp)

            success: function (msg, textStatus) 
            {//有數據返回時
                
                alert(msg.result);
                alert(msg.info);
                            
        
                }
            }

這個是js中ajax成功的片段代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM