$.ajax()是不能直接在自己的url属性中直接访问远程服务器的。
解决办法:
1.在$.ajax()的data:{}中写入要远程访问的服务器地址,作为参数数据传递到本地服务器;
2.在$.ajax()的url写入本地服务器;
3.通过本地服务器file_get_contents访问到远程服务器。
一、ajaxRemoteYes.html对ajax进行本地服务器请求:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>$.ajax解决跨域问题</title> <script src="../jquery-3.0.0.min.js"></script> </head> <body> </body> <script> $(function () { function postInfo() { $.ajax({ //访问服务器。从本地服务器跳转到远程访问的服务器 url: "ajax_post_fileGetContents.php", type: "post", 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); console.log(result.code); } }); } window.onload = postInfo(); }); </script> </html>
2.ajax_post_fileGetContents.php本地服务器接收ajax请求,并远程访问,接收远程数据返回给ajax。
<?php /** * Created by PhpStorm. * User: 洋 汪 * Date: 2016/7/20 * Time: 20:00 */ header("Content-type:text/html;charset=utf-8"); try { if ($_SERVER["REQUEST_METHOD"] == "POST") { //判断post的值是否存在 if (isset($_POST["url"]) && isset($_POST["username"]) && isset($_POST["password"])) { //传递数据参数,以数组形式。 $result = postTrans($_POST["url"], array("username" => $_POST["username"], "password" => $_POST["password"])); //注意返回的内容为什么 echo $result; } else { throw new Exception("数据不完整!!!"); } } else { throw new Exception("不是POST请求!!!"); } } catch (Exception $e) { echo json_encode(array("msg" => $e->getMessage())); } //传递过来的参数,以数组形式$data。 function postTrans($url, $data) { //发送到服务器之前应该如何对数据进行编码 //POST的4中编码格式: //1.(默认)application/x-www-form-urlencoded //2.multipart/form-data(上传文件时候) // 3.application/json // 4.text/xml //http_build_query()生成URL-encode之后的请求字符串。 $content = http_build_query($data); $requestPost = array( "http" => array( "header" => "Content-Type:application/x-www-form-urlencoded\r\n" . "Content-Length:" . strlen($content) . "\r\n" . "User-Agent:MyAgent/1.0\r\n", "method" => "POST", "content" => $content ) ); //转化为计算机的二进制流 $context = stream_context_create($requestPost); //进行跨域访问 $result = file_get_contents($url, false, $context, -1, 40000); //注意返回的内容为什么 return $result; } //echo postTrans("http://192.168.4.101:90/PHPStudy4/server.php", array("username" => "admin", "password" => "admin")); ?>