一个如何使用使 javascript 和 PHP 一起工作而不混淆它的示例(ajax):
首先你需要一个javascript函数:
function example()
{
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select // the variable you're posting.
},
success : function(data)
{
// This happens AFTER the PHP has returned an JSON array,
// as explained below.
var result1, result2, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
result1 = data[i].result1;
result2 = data[i].result2;
message = data[i].message;
// Do something with result and result2, or message.
// For example:
$('#content').html(result1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
现在我们需要在 ajax.php 中接收发布的变量:
$select = isset($_POST['select']) ? $_POST['select'] : false;
如果未设置,三元运算符让 $select 的值变为 false。
确保您可以在此处访问您的数据库:
$db = $GLOBALS['db']; // En example of a PDO database connection
现在,检查是否请求了 $select (true),然后执行一些数据库请求,并使用 JSON 返回它们:
if($select)
{
// Fetch data from the database.
// Return the data with a JSON array (see below).
]
else
{
$json[] = array
(
'message' => 'Not Requested'
);
}
echo json_encode($json);
flush();
您如何从数据库中获取数据当然是可选的,您可以使用 JSON 从数据库中获取单行,也可以使用它返回多行。
让我举一个例子,说明如何使用 json 返回多行(您将在 javascript(数据)中迭代):
function selectMultipleRows($db, $query)
{
$array = array();
$stmt = $db->prepare($query);
$stmt->execute();
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
foreach($result as $res)
{
foreach($res as $key=>$val)
{
$temp[$key] = utf8_encode($val);
}
array_push($array, $temp);
}
return $array;
}
return false;
}
然后你可以做这样的事情:
if($select)
{
$array = array();
$i = 0;
$query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
foreach(selectMultipleRows($db, $query) as $row)
{
$array [$i]["result1"] = $row['result1'];
$array [$i]["result2"] = $row['result2'];
$i++;
}
if(!(empty($array))) // If something was fetched
{
while(list($key, $value) = each($array))
{
$json[] = array
(
'result1' => $value["result1"],
'result2' => $value["result2"],
'message' => 'success'
);
}
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
或者,如果你想亲吻(保持简单愚蠢):
初始化一个从数据库中选择一些值并返回单行的基本函数:
function getSingleRow($db, $query)
{
$stmt = $db->prepare($query);
$stmt->execute();
// $stmt->execute(array(":id"=>$someValue)); another approach to execute.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
$array = (
'result1' => $result['result1'],
'result2' => $result['result2']
);
// An array is not needed for a single value.
return $array;
}
return false;
}
然后获取行(或单个值)并使用 JSON 返回:
if($select)
{
// Assume that the previously defined query exists.
$results = getSingleRow($db, $query);
if($results !== false)
{
$json[] = array
(
'result1' => $results['result1'],
'result2' => $results['result2'],
'message' => 'success'
);
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
无论如何,我希望我不会因为如此精确而在腿上开枪,但我喜欢这种技术,@Sabyre 想要一个例子,所以就在这里。如果您发现发生了奇怪的事情,请发表评论。