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