我正在尝试将 PHP API 调用的 JSON 结果传递给一个函数,该函数将在视图中显示结果。
script.js
功能
function ajaxProductsSearch() {
products.empty();
preloader.css('visibility', 'visible')
// Issue a request to the proxy
$.post('test.php', {
'search': searchBox.val()
}
function($results) { // pass $results from test.php?
if ($results.results_count == 0) {
preloader.css('visibility', 'hidden');
message.html("We couldn't find anything!").show();
return false;
}
$.each() { // code to display in view?
// var html = '';
// products.append(html);
};
preloader.css('visibility', 'hidden');
}, 'json');
}
基本上,您在视图中的文本框中输入搜索词,script.js
会将字符串发布到test.php
脚本,然后该脚本将运行API查询请求并按echo $results
显示结果。
这将首先显示您的结果,以便您可以继续开发。
function($results) { // pass $results from test.php?
if ($results.results_count == 0) {
...
}
// toString won't provide a nice output, but it will
// show your results object. Handling the results is
// dependent on the structure of your object.
message.html($results.toString());
}
我建议将消息替换为指向搜索结果容器元素的jQuery对象。
例如 <div id="search-results"></div>
和$("#search-results").html($results)
.
PHP返回一个JSON对象并使用javascript解析它从风格上更好,但我假设您目前只是返回一个包含结果的字符串。
我建议您查找以下函数:
- PHP
json_encode()
- jQuery
$.parseJSON()
更新
我终于让它工作了,如果有人感兴趣,下面是代码。我不确定我是否可以将$results
从 test.php
传递到 script.js
中的函数。 console.log($results)
帮助确认 API 查询成功并存储在 $results
中。
function ajaxProductsSearch(){
products.empty();
preloader.css('visibility','visible');
// Issue a request to the proxy
$.post('test.php', {
'search' : searchBox.val()
},
function($results) { // pass $results from test.php?
console.log($results);
if($results.results_count == 0){
preloader.css('visibility','hidden');
message.html("We couldn't find anything!").show();
return false;
}
$.each($results.results, function(i,item) { // code to display in view?
var html = '<a class="product" data-price="$ '+$results.results[i].price+'" href="'+$results.results.url+'" target="_blank">';
console.log($results.results[0]);
// If the product has images
if($results.results[i].images && $results.results[i].images.length > 0){
html += '<img alt="'+$results.results[i].name+'" src="'+ $results.results[i].images+'"/>';
}
html+='<span>'+$results.results[i].name.substr(0, 20)+'</span></a> ';
products.append(html);
});
preloader.css('visibility','hidden');
},'json');
}