当前位置:Gxlcms > JavaScript > ajax实现远程通信

ajax实现远程通信

时间:2021-07-01 10:21:17 帮助过:5人阅读

这篇文章主要介绍了ajax实现远程通信的相关资料,对ajax感兴趣的小伙伴们可以参考一下ajax实现远程通信文章

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

第一个文件:html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>ajax解决跨域问题</title>
  6. <script src="jquery-3.0.0.min.js" type="text/javascript"></script>
  7. </head>
  8. <body>
  9. <script>
  10. $.ajax({
  11. type:"POST",
  12. url:"postDemo.php",
  13. data:{
  14. "url":"http://192.168.4.101:90/PHPStudy4/server.php",
  15. "username":"admin",
  16. "password":"admin",
  17. },success:function(data){
  18. var result=eval("("+data+")");
  19. console.log(result);
  20. }
  21. })
  22. </script>
  23. </body>
  24. </html>

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

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2016-7-21
  6. * Time: 10:12
  7. */
  8. if ($_SERVER["REQUEST_METHOD"] == "POST") {
  9. // echo json_encode(array("111"=>"112"));
  10. if (isset($_POST["url"]) && isset($_POST["username"]) && isset($_POST["password"])) {
  11. $result = postDemo($_POST["url"], array("username" => $_POST["username"], "password" => $_POST["password"]));
  12. echo $result;
  13. } else {
  14. echo json_encode(array("msg2" => "!!!!!!!!!!!!!!!!!!!!!error!!!!!2"));
  15. }
  16. } else {
  17. echo json_encode(array("msg" => "error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"));
  18. }
  19. function postDemo($url, $data)
  20. {
  21. $query = http_build_query($data);
  22. $options = array(
  23. "http" => array(
  24. "header" => "Content-type: application/x-www-form-urlencoded\r\n" .
  25. "Content-length:" . strlen($query) . "\r\n" .
  26. "User-Agent:MyAgent/1.0/r/n",
  27. "method" => "POST",
  28. "content" => $query
  29. )
  30. );
  31. $content = stream_context_create($options);
  32. $result = file_get_contents($url, false, $content);
  33. return $result;
  34. }
  35. //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实现远程通信的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行