JQuery $.ajax()不能直接访问远程服务器,不能跨域访问。
现在我给出一个html写有js的用ajax不能远程访问服务器的例子:
ajaxRemoteNo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajaxRemote不能实现</title> <script src="../jquery-3.0.0.min.js"></script> </head> <body> <button οnclick="postInfo()">点击访问</button> <script> function postInfo() { $.ajax({ //直接远程访问,跨域访问地址。 url: "http://访问的IP地址:端口号/PHPStudy4/server.php", type: "post", success: function () { console.log("访问成功"); }, complete: function () { console.log("访问完成"); }, error: function () { console.log("访问出错"); } }); } </script> </body> </html>
点击访问后,爆粗错误如下:
XMLHttpRequest cannot load http://访问的ip地址:端口号/PHPStudy4/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8969' is therefore not allowed access.
并console.log()打印出:
访问出错
访问完成
我还会写出如何解决ajax跨域访问的方法,敬请关注我的博文。