我试图使用JQuery在url上从php中获取一个变量,并在javascript中使用该变量来更改页面上的内容。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$.get('http://jsonp.jit.su/?url=http://5.175.191.73/alert.php', function(data){
var alertstate=data.isit;
alert('pretty awesome, eh? ' + alertstate);
});
</script>
<script type="text/javascript">
if (alertstate==1) {
document.getElementById('theImg').src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Alert.gif";
play_single_sound(audiotag1);
}
</script>代码通过警报贯穿JQuery,但是一旦我到达Javascript语句,错误控制台就会告诉我,警报状态没有定义。任何帮助都将不胜感激。
发布于 2014-03-08 18:45:51
你有两个问题:
$.get是异步的,所以调用$.get的地方会启动ajax调用,但是在ajax调用异步发生时,代码会继续进行。因此,$.get后面的代码将在$.get完成之前运行。alertstate变量是作为对$.get的回调而给出的函数中的一个变量;它不存在于您的第二个代码块中,它希望它是一个全局变量。相反,将第二个脚本中的逻辑放入第一个$.get回调中:
<script>
$.get('http://jsonp.jit.su/?url=http://5.175.191.73/alert.php', function(data){
var alertstate=data.isit;
alert('pretty awesome, eh? ' + alertstate);
if (alertstate==1) {
document.getElementById('theImg').src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Alert.gif";
play_single_sound(audiotag1);
}
});
</script>如果您真的非常希望它们是独立的,您可以将所有内容封装在一个作用域函数中(以避免创建全局),使用回调关闭的变量,并使用$.get返回的承诺,如下所示:
<script>
(function() {
var alertstate, promise;
promise = $.get('http://jsonp.jit.su/?url=http://5.175.191.73/alert.php', function(data){
alertstate=data.isit;
alert('pretty awesome, eh? ' + alertstate);
});
promise.then(function() {
if (alertstate==1) {
document.getElementById('theImg').src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Alert.gif";
play_single_sound(audiotag1);
}
});
})();
</script>发布于 2014-03-08 18:43:48
$.get()是异步的,所以上面的代码不会按顺序执行。在下面的代码中,您需要在$.get() methos的成功回调中调用一个方法。
<script>
var alertstate;
$.get('http://jsonp.jit.su/?url=http://5.175.191.73/alert.php', function(data){
alertstate=data.isit;
alert('pretty awesome, eh? ' + alertstate);
playSound();
});
</script>
<script type="text/javascript">
function playSound(){
if (alertstate==1){
document.getElementById('theImg').src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Alert.gif";
play_single_sound(audiotag1);
}
}
</script>发布于 2014-03-08 18:47:30
问题在于范围。alertstate will only exist inside of your$.get`但不在它之外
$.get('http://jsonp.jit.su/?url=http://5.175.191.73/alert.php', function(data){
var alertstate=data.isit;
//You can use alertstate in here
alert('pretty awesome, eh? ' + alertstate);
});
//But not herehttps://stackoverflow.com/questions/22273481
复制相似问题