Javascript没有输入带有.php文件引用的函数


Javascript not entering function with .php file reference

长期寻求答案者,第一次提问者。

我正在配置一小段js,它在页脚中被引用:

<script type='text/javascript' src='http://test.site.com/wp-content/themes/spacious/js/jsfile.js?ver=1.0.5'></script>

这是输入的html:

<div>
    <form id="search" action="" method="POST">
        <input type="text" id="str" name="str" value="" />
        <input type="submit" value="search" />
    </form>
    <div id="search_results"></div>
</div>

js脚本文件如下:

(function func() {
    $("#search").bind('submit', function () {
        var value = $('#str').val();
        $.post('db_query.php', {
            value: value
        }, function (data) {
            $("#search_results").html(data);
        }); 
        return false;
    });
});

php文件如下:

<?php
    try {
        $db = new PDO('sqlsrv:Server=xx.xx.xx.xx;Database=xxxx','user','pass');
    }
    catch (Exception $e) {
        echo 'PDO connection error: ' . $e->getMessage();
        exit(1);
    }
    $sql=$db->prepare("SELECT top 20 Timestamp,Information,Location FROM Table WHERE JobReference = :val");
    $sql->execute(array(':val'=>$_REQUEST['value']));
    echo '<table>';
    echo '<th>Date Time</th><th>Information</th><th>Location</th>';
    while ($row=$sql->fetch())
    {
        echo "<tr><td>$row[Timestamp]</td><td>$row[Information]</td><td>$row[Location]</td></tr>";
    }
    echo '</table>';
?>

当我尝试使用Chrome进行调试时,它会在第一个"("处停止,然后跳到函数的末尾。起初我以为这是因为引用了.php文件,但似乎根本没有命中它?

我不知道该怎么办。。。

非常感谢,卡梅伦。

您只是在声明一个名为func的JavaScript函数。但是,为了使代码正常工作,您还必须调用该函数。

在函数末尾添加另一个括号,如下所示:

(function func() {
$("#search").bind('submit', function () {
    var value = $('#str').val();
    $.post('db_query.php', {
        value: value
    }, function (data) {
        $("#search_results").html(data);
    }); return false;
  });
})();

除了@Nano答案,您还可以这样修复:

(function($) { //pass $ as jQuery in this scope
$("#search").bind('submit', function () {
    var value = $('#str').val();
    $.post('db_query.php', {
        value: value
    }, function (data) {
        $("#search_results").html(data);
    }); return false;
  });
})(jQuery); //$ is jQuery