ajax实现远程通信

6 篇文章 0 订阅
5 篇文章 0 订阅

第一个文件;html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax解决跨域问题</title>
    <script src="jquery-3.0.0.min.js" type="text/javascript"></script>
</head>
<body>
<script>
    $.ajax({
        type:"POST",
        url:"postDemo.php",
        data:{
            "url":"http://192.168.4.101:90/PHPStudy4/server.php",
            "username":"admin",
            "password":"admin",
        },success:function(data){
            var result=eval("("+data+")");
            console.log(result);
        }

    })
</script>
</body>
</html>

第二个文件  服务器端处理数据

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016-7-21
 * Time: 10:12
 */

if ($_SERVER["REQUEST_METHOD"] == "POST") {
//    echo json_encode(array("111"=>"112"));
    if (isset($_POST["url"]) && isset($_POST["username"]) && isset($_POST["password"])) {
        $result = postDemo($_POST["url"], array("username" => $_POST["username"], "password" => $_POST["password"]));
        echo $result;

    } else {
        echo json_encode(array("msg2" => "!!!!!!!!!!!!!!!!!!!!!error!!!!!2"));
    }
} else {
    echo json_encode(array("msg" => "error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"));
}
function postDemo($url, $data)
{

    $query = http_build_query($data);
    $options = array(
        "http" => array(
            "header" => "Content-type: application/x-www-form-urlencoded\r\n" .
                "Content-length:" . strlen($query) . "\r\n" .
                "User-Agent:MyAgent/1.0/r/n",
            "method" => "POST",
            "content" => $query
        )
    );
    $content = stream_context_create($options);
    $result = file_get_contents($url, false, $content);
    return $result;
}

//echo postDemo("http://192.168.4.101:90/PHPStudy4/server.php",array("username"=>"admin","password"=>"admin"));
其中
"url":"http://192.168.4.101:90/PHPStudy4/server.php",
这个url就是我们向远端的访问地址.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值