Mui.ajax请求服务器正确返回json数据格式

ajax:

mui.ajax('http://server-name/login.php',{
    data:{
        username:'username',
        password:'password'
    },
    dataType:'json',//服务器返回json格式数据
    type:'post',//HTTP请求类型
    timeout:10000,//超时时间设置为10秒;
    success:function(data){
        //服务器返回响应,根据响应结果,分析是否登录成功;
        ...
    },
    error:function(xhr,type,errorThrown){
        //异常处理;
        console.log(type);
    }
});

后台php:

<?php  
    header('Content-type:text/html; Charset=utf8');  
    header( "Access-Control-Allow-Origin:*");  
    header('Access-Control-Allow-Methods:POST');    
    header('Access-Control-Allow-Headers:x-requested-with,content-type');   
    include('../../conn.php');  
    include('../../luanma.php');  
      
    $sql="select *  from news where class='校园新闻' order by time ASC";  
    mysql_query("SET NAMES utf8");  
    $result= mysql_query($sql);   
    while($array=mysql_fetch_array($result ,MYSQL_ASSOC)){  
          
        $tt[]=array('tittle'=>$array["tittle"],'txt'=>$array["text"],'source'=>$array['source'],'date'=>$array['date']);  
          
          
    }  
    echo json_encode($tt);  
      
        mysql_close();  
      
        ?>  

必不可少的:

    header('Content-type:text/html; Charset=utf8');  
    header( "Access-Control-Allow-Origin:*");  
    header('Access-Control-Allow-Methods:POST');    
    header('Access-Control-Allow-Headers:x-requested-with,content-type');  

转自kevin_cyj,略做了写修改,原博客地址 http://blog.csdn.net/kevin_cyj/article/details/51090668
原文地址:https://www.cnblogs.com/phoebewang00/p/6250527.html