网页前端用JQ之$.ajax处理PHP返回的json数据

后端开发   发布日期:2023年05月15日   浏览次数:247

HTML页面中引用的JQ处理AJAX($.ajax)的代码:

发送的数据也是用的JSON格式,后台PHP也要对应处理获取的JSON数据。

$.ajax({
    type: "POST",
    timeout: 5000,
    // 设置超时时间
    url: Test_Url,
    contentType: "application/json", //如果提交的是json数据类型,则必须有此参数,表示提交的数据类型 
    //dataType: "json", //如果注释掉表示字符型
    dataType: "json",   //表示返回值类型为JSON。
    data: JSON.stringify({
        "action": 'yanzheng',
        "jiqima": jiqima_val
    }),
    success: function(jsonResult) {
        //console.log(jsonResult.back_status)
        var back_status = jsonResult.back_status;
        if (back_status == 'null') { //为空
            $("#show_error").html("终端识别码不能为空!")
        } else if (back_status == 'error') { //错误
            $("#show_error").html("终端识别码验证失败!")
        } else if (back_status == 'ok') { //正常
            localStorage.setItem("jiqima_data", jiqima_val) $("#show_error").html("<span style=color:green>验证通过!【" + jsonResult.mingcheng + "】</span>") setTimeout(function() {
                top.location.href = jsonResult.url;
            },
            2000);
        }
    },
    // 例如以下错误:  /Not Found/error/timeout
    error: function(data) {
        setTimeout(function() {
            jiqima_over(v)
        },
        1000);
    }
});

PHP后台接收前台POST过来的JSON数据,并返回JSON格式数据给$.ajax进行处理:

$post_val=file_get_contents('php://input');//jq ajax的json数据用此方法接收
$post_str=json_decode($post_val, true);
$action=$post_str['action'];

......自己的PHP逻辑代码

//以下是PHP返回的JSON结构的数据
echo '{"back_status":"ok","mingcheng":"'.$z_mingcheng.'","url":"'.$url.'"}';
exit;


以上就是网页前端用JQ之$.ajax处理PHP返回的json数据的详细内容,更多关于网页前端用JQ之$.ajax处理PHP返回的json数据的资料请关注九品源码其它相关文章!