我已经花了大约 3 个小时尝试了很多不同的方法,但我显然做错了一些事情,而且似乎无法理解。
我有一个 php 文件,它从变量 $tweeturl 中的另一个 php 脚本生成 url:
tweet.php
<?php
$ch = curl_init("http://path/to/data.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$doit = curl_exec($ch);
$dom = new DOMDocument();
@$dom->loadHTML($doit);
$show = $dom->getElementById("showmeta");
$liveshow = $show->nodeValue;
$dj = $dom->getElementById("djmeta");
$livedj = $dj->nodeValue;
$npshow = $liveshow;
$npshow = preg_replace('/\s+/', '+', $npshow);
$npdj = $livedj;
$npdj = preg_replace('/\s+/', '+', $npdj);
$url1 = "https://twitter.com/intent/tweet?source=webclient&text=Listening+to+";
$url2 = $npshow;
$url3 = $npdj;
$tweeturl .= $url1;
$tweeturl .= $url2;
$tweeturl .= $url3;
?>
这已经过测试并且工作正常。
我正在尝试通过 AJAX 将变量放入 JQuery 中,以填充空白浏览器窗口的 url(我使用的是 wordpress,这就是包装该函数的原因):
HTML
<a class="player-twitter" href="#"</a>
JQuery
<script type="text/javascript">
(function($) {
$(document).ready(function() {
$( "a.player-twitter" ).click(function( event ) {
$.ajax({
type: "GET",
url: "http://path/to/tweet.php",
data: { var: $tweeturl },
success: function(e) {
window.open(<?php echo $tweeturl; ?>);
}
});
})
});
})( jQuery );
</script>
我知道我做错了,但我就是不知道我做错了什么。
任何帮助将不胜感激。
编辑以显示此处收到帮助后的工作脚本
虽然所有答案都是正确的,但很多答案都超出了我此处不需要的 JSON 转换。我真的很感激,因为我从中学到的东西比我预期的要多。但如果像我一样,您只想从 php 脚本中获取单个 var,这就是应该如何完成的...
tweet.php(与原始问题相同,但在末尾添加了以下回显)
echo $tweeturl;
天真地我只是期望 JQuery 能够识别 $tweeturl 变量,而不必实际回显它。哦!
JQuery
<script type="text/javascript">
(function($) {$(document).ready(function() {
$( "a.player-twitter" ).click(function( event ) {
$.ajax({
type: "GET",
url: "http://path/to/tweet.php",
success: function ( response_string ) {
window.open( response_string );
}
});
})
});})( jQuery );
</script>
再次感谢你们所有的帮助,不仅帮助我完成这项工作,还解释了一些我不理解的有关 JQuery 的事情。
最佳答案
现在这里有一些使用 JSON 的答案。但这在您的示例中是不必要的,因为您只想返回一个字符串。所以这是一个简单的解决方案:
在 PHP 中,您必须输出想要返回到 ajax 调用的内容。所以只需将其添加到 PHP 文件的末尾即可:
echo $tweeturl;
在你的 javascript 中更改你的 ajax 调用:
$.ajax({
type: "GET",
url: "http://path/to/tweet.php",
success: function ( response_string ) {
window.open( response_string );
}
});
就是这样 - 当您不向 PHP 文件发送任何数据时,您甚至不需要此处的 data:..
。
关于php - 将 PHP var 从远程 PHP 脚本获取到 JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27525572/