使用ajax无法跨源问题总结

参考文章:

浏览器同源政策及其规避方法

跨域资源共享 CORS 详解

使用jQuery实现跨域提交表单数据

  1. <form action="http://v.juhe.cn/weather/index">
  2.     <label>输入要查询的城市名称:<input type="text" name="cityname" id="cityname" placeholder="北京"></label>
  3.     <button type="submit" id="show">查询</button>
  4. </form>

方法1:

  1. function addScriptTag(src){
  2.     var script=document.createElement("script");
  3.     script.setAttribute("type","text/javascript");
  4.     script.src=src;
  5.     document.body.appendChild(script);
  6. }
  7. function foo(data) {
  8.     console.log(data.result.today);
  9. }
  10. $(document).ready(function(){
  11.     //当发生 submit 事件时运行的函数
  12.     $("form").submit(function(e){
  13.         addScriptTag("http://v.juhe.cn/weather/index?   cityname=%E8%8B%8F%E5%B7%9E&key=47ae6e500980056c1defce105b3a90c3&callback=foo");
  14.     });
  15. })

 

方法2:

参考文章:http://www.helloweba.com/view-blog-166.html

  1. $(document).ready(function(){
  2.     var data=$("form").serialize(); //输出序列化表单值的结果
  3.     data+="&key=47ae6e500980056c1defce105b3a90c3";
  4.     $.getJSON("http://v.juhe.cn/weather/index?callback=?",
  5.         data,
  6.         function (responseText) {
  7.        conlo.log(responseText);
  8.         }
  9.     );
  10. });
原文地址:https://www.cnblogs.com/jeacy/p/6593195.html