ajax实现远程通信
作者: default|标签:AJAX 通信 实现|2018-1-13 11:41
这篇文章主要介绍了ajax实现远程通信的相关资料,对ajax感兴趣的小伙伴们可以参考一下ajax实现远程通信文章

本文实例为大家分享了ajax实现远程通信,供大家参考,具体内容如下

第一个文件: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就是我们向远端的访问地址.

相关推荐:

ajax同步验证单号是否存在

js和ajax处理java后台返回的json对象

Ajax获取数据然后显示在页面方法

以上就是ajax实现远程通信的详细内容,更多请关注php中文网其它相关文章!

10
点赞
收藏
分享:
0/300