未定义全局变量。从Ajax调用成功

时间:2022-11-05 19:45:48

So i´m trying to implement Jquery "Autocomplete" on a input field.
And i like Ajax to fetch "tags" from mysql.

所以我想在输入字段上实现Jquery“Autocomplete”。我喜欢Ajax从mysql中获取“标签”。

HTML

<input type="text" id="autocomplete">

I´ve tried several stuff and googled around. I can found larger codes, but this should really be enough!?

我尝试了几种东西并用Google搜索。我可以找到更大的代码,但这应该足够了!?

JS

//Get objNr from db
$.ajax({
    url: 'file.php',
    success: function(result){
        //Here i make the result global
        objNrs = result;
    }
});
$( "#autocomplete").autocomplete({
    source: objNrs,
});

To se if there was an empty result from php i added echo 'Hello';

如果有一个来自php的空结果我添加echo'Hello';

PHP

while($row = $stmt->fetch()){
    //Here i tried to use `json_encode`
    echo $row['objekt_nr'];
}
echo "Hello";

My browser console tell me that source: objNrs,
"objNrs is not defined"

我的浏览器控制台告诉我源:objNrs,“objNrs未定义”

So, whats my problem?
Isn´t the variable global at all?

那么,我的问题是什么?这个变量根本不是全球性的吗?

1 个解决方案

#1


2  

Ajax run asynchronously, so your autocomplete code will execute before the ajax getting success. so you need to write the autocomplete code inside successs event.

Ajax以异步方式运行,因此您的自动完成代码将在ajax成功之前执行。所以你需要在successs事件中编写自动完成代码。

$.ajax({
    url: 'file.php',
    success: function (result) {
        //Here i make the result global
        objNrs = result;
        $("#autocomplete").autocomplete({
            source: objNrs,
        });
    }
});

#1


2  

Ajax run asynchronously, so your autocomplete code will execute before the ajax getting success. so you need to write the autocomplete code inside successs event.

Ajax以异步方式运行,因此您的自动完成代码将在ajax成功之前执行。所以你需要在successs事件中编写自动完成代码。

$.ajax({
    url: 'file.php',
    success: function (result) {
        //Here i make the result global
        objNrs = result;
        $("#autocomplete").autocomplete({
            source: objNrs,
        });
    }
});