繁体   English   中英

将php数组传递给Ajax / jQuery

[英]passing php array to Ajax/jQuery

大家好我知道这个主题有一些结果,但我并没有尝试做任何太高级的事情,只是试图了解基础知识。 由于某种原因,此代码警报工作并打印出正确的数组信息,但我似乎无法让它适用于自动完成? https://jqueryui.com/autocomplete/

var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
    var res = oReq.responseText;
    AC(res);
};
oReq.open("get", "get-data.php", false);
oReq.send();

function AC(res){
$(function() {
    alert(res);
    $( "#tags" ).autocomplete({
      source: res
    });
});
}

所以警报(res)在函数AC()中工作,但它仍然没有填充源?

我的get-data.php看起来像这样

<?php $arr = array("ActionScript",
      "AppleScript",
      "Asp");

echo json_encode($arr); ?>

即使我需要更多信息,我也会感激任何指导

JSON.unserialize在javascript中。

source: JSON.parse(res);

这是因为未解码的JSON。 JSON以字符串形式到达,因此alert()可以正常显示接收的数据,但是当您发布到源时,您必须发布对象 - 需要将字符串解码为对象。 ;)结果代码:

var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
    var res = oReq.responseText;
    AC(res);
};
oReq.open("get", "get-data.php", false);
oReq.send();

function AC(res){
$(function() {
    alert(res);
    $( "#tags" ).autocomplete({
      source: JSON.parse(res)
    });
});
}

HTH

暂无
暂无

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

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