php+JavaScript 实现前后端JSON交互(GET/POST)

注:jsonp方式可解决跨域访问的问题,即:读者将前端代码copy至本地,可以发现笔者服务器提供的json接口依然是可用的。

有兴趣可到下面链接在开发者模式下体会交互过程。
http://www.yixzm.cn/public_api_view/json_server_html

前端代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSONP 实例</title>
</head>
<body>
    <p>callback:</p><div id="divCallBackJson"></div>
    <p>post:</p><div id="divPostJson"></div>

    <script type="text/javascript">

function callbackFunction(result, methodName)
{
    var html = '<ul>';
    for(var i = 0; i < result.length; i++)
    {
        html += '<li>' + result[i] + '</li>';
    }
    html += '</ul>';
    document.getElementById('divCallBackJson').innerHTML = html;
}
//<!-- post 方式 -->
function postJson()
{
    var msgJson = '{"mainElements":["main_1","main_2"],"tipElements":["tip_1"],"subElements":["sub-1"]}';
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById('divPostJson').innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","/public_api_json/post_json",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("msgJson="+msgJson);
    console.log(msgJson="+msgJson");
}


postJson();

</script>
<!-- jsonp 方式 -->
<script type="text/javascript" src="http://www.yixzm.cn/public_api_json/callback_json?jsoncallback=callbackFunction"></script>
</body>
</html>

后端代码

public function callback_json()
{
    header('Content-type: application/json');
    //获取回调函数名
    $jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
    //json数据
    $json_data = '["jsondata1","jsondata2"]';
    //输出jsonp格式的数据
    echo $jsoncallback . "(" . $json_data . ")";
}

public function post_json()
{
    $json_data = NULL;

    if (isset($_POST['msgJson'])) {
        $json_data = $_POST['msgJson'];
    }
    echo $json_data;
}

猜你喜欢

转载自blog.csdn.net/dreamstone_xiaoqw/article/details/80397693
今日推荐