我必须制作一个JSON ajax请求并返回一个数组。
我在其他多个问题上找到了这个代码(根据我的问题编辑):
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
var data = response.get_response;
for (i in data){
hej.push([i,data[i]]);
}
alert(hej[0]);
}
在php部分,我有一个数据库,我需要数据,我有5列pr。行。我只有一行,我需要数组中的所有五列。
$sql = "SELECT * FROM 'table'
LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = Array();
while($row = mysql_fetch_array($result))
{
$storeArray[0]=$row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode($storeArray);
echo $json;
我知道我做错了什么,而且我是编程新手。我需要能够在调用后访问我的javascript中的所有列值并在其他函数中使用它们,但我不能让它返回。
如果两者都有错误,我会用javascript和php来提供帮助。
答案 0 :(得分:0)
为什么要使用response.get_response?
var hej[];
function ajax_search(){
$.getJSON('test.php',function(data){
$.each(data, function (i,item) {
hej.push([i,item]);
}
alert(hej[0]);
}
答案 1 :(得分:0)
试试这个:
Javascript代码:
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
$.each(response.results, function(key, val) {
hej.push(val);
});
alert(hej[0]);
});
}
PHP代码:
<?php
$sql = "SELECT * FROM 'table' LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = array();
while($row = mysql_fetch_array($result)) {
$storeArray[0]= $row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode( array('results' => $storeArray ) );
echo $json;
?>
希望这有帮助。
答案 2 :(得分:0)
应该是:
function ajax_search(){
$.getJSON('test2.php',function(response){
// response.column1
// response.column2
// response.column3
// for array push:
var hej = [];
$.each(response, function(key, val) {
hej.push(val);
});
alert(hej[0]); // it will alert column1
});
}
和MySQL:
$sql = "SELECT `column1`, `column2`, `column3`, `column4`, `column5` FROM `table` LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$json = json_encode($row);
echo $json;