简体   繁体   English

错误:在jquery函数中对服务器的Ajax调用

[英]Error : Ajax call to server inside jquery function

I am trying to make an ajax call to a server in my local network installed with LAMP who is running wordpress. 我正在尝试对本地局域网中安装了运行wordpress的LAMP的服务器进行ajax调用。 I am currently doing changes to files in a wordpress plugin. 我目前正在对wordpress插件中的文件进行更改。

I want to call a php file located into my server to get json data to build a chart from a sql request. 我想调用位于服务器中的php文件来获取json数据,以根据sql请求构建图表。

So I have ajaxStatistics.php where I coded the sql request and the json encode. 所以我有ajaxStatistics.php,在其中我编码了sql请求和json编码。

Now I am in statistics.js where I have my function to build a chart and this is where I do the ajax call : 现在,我在statistics.js中,我具有构建图表的功能,这是我进行ajax调用的地方:

jQuery(function() { 
    /**
     * call the ajaxStats.php file to fetch the result from db table.
     */
    $.ajax({
        url : "192.168.1.100/wp-content/plugins/pluginname/ajaxStatistics.php",
        type : "GET",
        success : function(data){
            console.log(data);
            ...

The result is an Uncaught TypeError: Cannot read property 'ajax' of undefined 结果是未捕获的TypeError:无法读取未定义的属性'ajax'

at HTMLDocument.<anonymous> (statistics.js:92)
    at i (jquery.js?ver=1.12.4:2)
    at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
    at Function.ready (jquery.js?ver=1.12.4:2)
    at HTMLDocument.K (jquery.js?ver=1.12.4:2)

You are trying to access $ as jQuery before it gets initialized so to make it in proper way, you can use DOM load event of it like so... 您正在尝试在$ $初始化之前将$作为jQuery访问,以便以正确的方式进行操作,您可以像这样使用它的DOM load事件...

$(document).ready(function(){
    function build_statistics() {
        $.ajax({
        url : "http://192.168.1.100/wp-content/plugins/pluginname/ajaxStatistics.php",
        type : "GET",
        success : function(data){
            console.log(data);
        }
    }
});

And then call it like 然后像这样称呼它

build_statistics()

That means that jquery has not been loaded. 这意味着尚未加载jquery。

Make sure that you have the script in your html, and also wrap the call to this function sendData inside a 确保您的html中包含脚本,并且还将对此函数sendData的调用包装在

$(document).ready(function(){
//do stuff
})

It seems like your $ variable is unreachable in your code. 看来您的$变量在代码中无法访问。

Try this: 尝试这个:

jQuery(function() { 
    /**
     * call the ajaxStats.php file to fetch the result from db table.
     */
    var $ = jQuery;

    $.ajax({
        url : "http://192.168.1.100/wp-content/plugins/pluginname/ajaxStatistics.php",
        type : "GET",
        success : function(data){
            console.log(data);
            ...

And also make sure to add a http or https in your url. 还要确保在您的网址中添加httphttps

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM