jQuery AJAX请求,语法错误

jQuery AJAX Request, Incorrect Syntax?

本文关键字:语法 错误 请求 AJAX jQuery      更新时间:2023-09-26

从我的语法可以看出,我对jQuery非常陌生。我得到一个错误

Uncaught SyntaxError: Unexpected identifier

我代码:

jQuery(document).ready(function () {
    //trying to reload the content after 3 seconds.
    setTimeout( "jQuery('#div1').load("ajaxtest.php");",3000 );
});

试试这个,你会想把你的jquery动作放在一个函数中,像这样:

jQuery(document).ready(function () {
    //trying to reload the content after 3 seconds.
    setTimeout(function(){
        jQuery('#div1').load("ajaxtest.php");
    }, 3000 );
});

Try with:

jQuery(document).ready(function () {
    //trying to reload the content after 3 seconds.
    setTimeout( function() { $('#div1').load("ajaxtest.php")},3000 );
});

如果你需要循环,这应该是合适的:

jQuery(document).ready(function () {
    //trying to reload the content after 3 seconds.
    setInterval( function() { $('#div1').load("ajaxtest.php"); },3000 );
});

问题在于""里面的""

下面是如何使用转义字符 来纠正它
jQuery(document).ready(function () {
   //trying to reload the content after 3 seconds.
   setTimeout( "jQuery('#div1').load('"ajaxtest.php'");",3000 );
});

但是在setTimeout中传递字符串被认为是不好的做法。所以,你可以试试经典的enclosure

jQuery(document).ready(function () {
    //trying to reload the content after 3 seconds.
    setTimeout((function(){jQuery('#div1').load("ajaxtest.php");}),3000 );
}); 

循环使用setInterval

jQuery(document).ready(function () {
    //trying to reload the content after 3 seconds.
    setInterval((function(){jQuery('#div1').load("ajaxtest.php");}),3000 );
}); 

要停止循环你可以使用像这样的变量

 var anything = 
     setInterval((function(){jQuery('#div1').load("ajaxtest.php");}),3000 );

和最后清除

 clearInterval(anything);