跨域Ajax的动态脚本标记无法正常工作

时间:2011-07-20 07:50:07

标签: php javascript ajax cross-domain

我正在尝试使用动态脚本标记进行跨域ajax,因为我不能在需要它的网站上使用PHP(我们使用的是CMS,所以我们可以使用HTML / Javascript,但是没有PHP)。

问题是,这两个脚本都可以自行运行(javascript和php),这意味着脚本标记很好地添加,并且PHP脚本在自行启动时可以根据需要运行。

但是添加脚本标记(使用.appendChild)时,看起来没有处理GET请求。

有没有办法让它发挥作用?

以下是代码,简化:

PHP:

$email = $_GET['email'];
$source = $_GET['source'];
echo 'callback({"value": "true"});';
// sending the email through php

Javascript:

function dlPj() {
  // Prompt the user for his email
  var email = prompt('Enter your email', 'your email');
  // If the script tag already exists, delete it
  if (document.getElementById('script-pj') != null) {
    var script_pj = document.getElementById('script-pj');
    document.getElementsByTagName("head")[0].removeChild(script_pj);
  }
  // Create the script tag to call the PHP script
  var s = document.createElement('script');
  s.type = 'txt/javascript';
  s.id = 'script-pj';

  s.src = 'http://www.something.com/bel/pj.php?';
  s.src += 'email=' + email;
  s.src += '&source=' + document.location.href + '?';

  document.getElementsByTagName("head")[0].appendChild(s);
}

function callback(value) {
  if (value == null) {
    alert('error');
  }
  else {
    if (value.value == "true") {
      alert('working');
    }
    else {
      alert('not working');
    }
  }
}

非常感谢。

编辑:问题已解决。问题如下:我在A标记上添加了一个onclick事件,以便在下载附件之前我可以获得有关用户的一些信息。所以我把它留在了返回true;,以便他可以在填写表格后下载文件。将onclick事件更改为“dlPj();返回false;”解决了这个问题。

2 个答案:

答案 0 :(得分:0)

试试这个,它适用于chrome:

  var email = prompt('Enter your email', 'email@company.com');
  // If the script tag already exists, delete it
  if (document.getElementById('script-pj') != null) {
    var script_pj = document.getElementById('script-pj');
    document.getElementsByTagName("head")[0].removeChild(script_pj);
  }
  // Create the script tag to call the PHP script
  var s = document.createElement('SCRIPT');
  s.id = 'script-pj';
  s.src = 'http://www.something.com/bel/pj.php?' +
                'email=' + encodeURIComponent(email) + 
                '&source=' + encodeURIComponent(document.location.href);

  document.getElementsByTagName("head")[0].appendChild(s);

答案 1 :(得分:0)

好吧,所以这正确遵循stackoverflow的工作流程,有答案。

问题如下:我在A标签上添加了onclick事件,以便在下载附件之前我可以获得有关用户的一些信息。所以我把它留在了返回true;,以便他可以在填写表格后下载文件。将onclick事件更改为“dlPj();返回false;”解决了这个问题。