George_Fal 2012-04-25 13:21 采纳率: 0%
浏览 60

如何使用ajax从外部域获取变量?

我正在尝试使用ajax从外部域获取变量,然后使用数据创建预填充的表单字段,但是我似乎无法使其正常工作。 我对JavaScript有点陌生,我实在无法弄清为什么它不起作用。

 <html>
<head>
<script type="text/javascript">
    function xss_ajax(url) {
        var script_id = null;
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', url);
        script.setAttribute('id', 'script_id');

        script_id = document.getElementById('script_id');
        if(script_id){
            document.getElementsByTagName('head')[0].removeChild(script_id);
        }

        // Insert <script> into DOM
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    function callback(data) {

    var counter = 1;
    var limit = 3;
    var txt = '';

    for(var key in data) {

          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]' value=" + data[key] +">";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
;
        }
    }

    var url = "http://myserver.com/test.php";

</script>
<title></title>
</head>
<body>
<button onclick="xss_ajax(url);">Get Data</button>
</body>
</html> 

外部域上的脚本:

callback({"firstname":"John", "lastname":"Smith", "email":"john.smith@johnsmith.com"});
  • 写回答

1条回答 默认 最新

  • weixin_33696822 2012-04-25 13:23
    关注

    You need to look into JSONP. Also using a library to handle the request will help exponentially, checkout jQuery or Extjs. Heres a blog post that should give you a hand.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器