【发布时间】:2011-09-01 22:18:02
【问题描述】:
我正在尝试将动态脚本标签用于跨域 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 事件,这样我就可以在用户下载附件之前获得一些关于用户的信息。所以我把它留在了return true;,这样他就可以在填写表格后下载文件。将 onclick 事件更改为“dlPj(); return false;”解决问题。
【问题讨论】:
-
脚本类型应该是“text/javascript”。是不是打错字了?
-
哦,对了,打错了。但这并没有改变任何问题:-)
-
实际上,浏览器可能会拒绝获取任何类型无法识别的脚本。你用“text/javascript”试过了吗?
-
我做到了。我也没有类型。
-
@Florian 我投票给你。这是我能为你做的最多的事情:-)
标签: php javascript ajax cross-domain