Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在$(document).ready(function(){})中调用JavaScript函数_Javascript_Jquery_Ajax - Fatal编程技术网

在$(document).ready(function(){})中调用JavaScript函数

在$(document).ready(function(){})中调用JavaScript函数,javascript,jquery,ajax,Javascript,Jquery,Ajax,我想在页面加载和onChange中运行ajax函数,下面是我的代码: function ajax_get_subject(ID) { alert('function called'); $.ajax( { type: 'POST', url: 'ajax_get_subject.php', data: {CourseID: ID}, dataType: 'json', success: fu

我想在页面加载和
onChange
中运行ajax函数,下面是我的代码:

function ajax_get_subject(ID)
{
    alert('function called');
    $.ajax(
    {
        type: 'POST',
        url: 'ajax_get_subject.php', 
        data: {CourseID: ID},
        dataType: 'json',
        success: function(data)
        {
            if(data['error'] == null)
            {
                //do something
            }
            else
            {
                //do something
            }
        },
        error: function(ts)
        {
            alert("AJAX Error: \n" + ts.responseText);
        }
    });
}
下面是
ready()
函数,我在其中调用
ajax\u get\u subject
函数:

$(document).ready(function()
{
    //populate at 1st when page load
    $(function()
    {
        var ID = <?php echo $CourseID?>;
        ajax_get_subject(ID);
    });
});
$(文档).ready(函数()
{
//页面加载时在第一个位置填充
$(函数()
{
变量ID=;
ajax_get_subject(ID);
});
});

未触发函数
ajax\u get\u subject
。但是如果我在$('element').change()中调用该函数,它就会工作。我的代码有什么问题吗?

我认为您试图在不是由PHP执行的JS文件中使用PHP代码。您必须将声明移动到HTML文件的某个位置

建议的解决方案 我经常在文件顶部定义PHP值,以便在JavaScript中使用它们,例如:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript">
            window.phpValues = window.phpValues || {};
            window.phpValues.courseId = '<?php echo $CourseId ?>';
        </script>
        <script type="text/javascript" src="path/to/your/script.js">
    </head>
    ....
</html>

我有一个语法错误,在第
varid=行,谢谢@Felix Kling在评论中提及
$CourseID
的值是一个字符串,但没有双引号,我只需将代码更改为
var ID=”“并且它可以工作
同时也感谢您提到嵌套的
document.ready()问题

请问
$courseID
的值是多少?我假设您有语法错误(请查看控制台)。另外,不需要有两个嵌套的
document.ready
调用。删除
$(document).ready(…)
$(function(){…})
<代码>警报
不是调试工具。使用浏览器的开发工具,
console.log
和断点。我认为您试图在不是由PHP执行的JS文件中使用PHP代码。您必须将声明移到HTML文件的某个位置
var ID=$(function(){})
嵌入
$(document.ready()
中。毫无意义。两者都在做同样的事情。
$(window).ready(function() {
    alert(phpValues.courseId); // alerts value of $CourseID
});