我试图使用跨域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();返回false;"解决问题。
试试这个,它在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);
好了,这样就可以正确地遵循stackoverflow的工作流程,这就是答案。
问题是这样的:我在A标签上添加了一个onclick事件,这样我就可以在用户下载附加文件之前获得一些关于他的信息。所以我把它留在了return true;,这样他填完表格后就可以下载文件了。将onclick事件更改为"dlPj();返回false;"解决问题。