我正在尝试为我的Project构建一个查询构建器,我可以在其中传递任何数组,执行SELECT语句,返回结果并将其格式化为JavaScript。
我已经尝试了几天才能让它工作,但我在PHP方面有点新手,坦率地说这些手册似乎没什么帮助。
首先,我构建以下数组:
for(var i = 0; i < FormSelect.length; i++){
if(FormSelect[i].selectedIndex != 0){
if(WhereClause.length == 0){
var WhereObject = {
ColumnName: FormSelect[i].id,
ColumnValue: FormSelect[i].value
}
}
else{
var WhereObject = {
Operator: " AND ",
ColumnName: FormSelect[i].id,
ColumnValue: FormSelect[i].value
}
}
}
WhereClause.push(WhereObject);
}
然后我按如下方式将请求发送到服务器,一切正常:
var FormSearchData =
"ColumnNames=" + ColumnNames
+ "&"
+ "ViewName=" + ViewName
+ "&"
+ "WhereClause=" + WhereClause
+ "&"
+ "FormSearchExecuted=1"
var FormSearchXMLHTTPRequest = new XMLHttpRequest();
FormSearchXMLHTTPRequest.onload = function(){
console.log(FormSearchXMLHTTPRequest.responseText);
}
FormSearchXMLHTTPRequest.open("POST", RootData + "global/search/search.php", false);
FormSearchXMLHTTPRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
FormSearchXMLHTTPRequest.send(FormSearchData);
PHP中的服务器端是问题开始的地方。
if(isset($_POST["FormSearchExecuted"]) && !empty($_POST["FormSearchExecuted"])){
if(empty($_POST["ColumnNames"])){
$column_names = "*";
}
else{
$column_names = $_POST["ColumnNames"];
}
if(!empty($_POST["WhereClause"])){
if(count($_POST['WhereClause']) == 1){
$form_search_sql = "DECLARE @ColumnNames VARCHAR SET @ColumnNames = ? DECLARE @ViewName VARCHAR(255) SET @ViewName = ? DECLARE @WhereColumn VARCHAR SET @WhereColumn = ? DECLARE @WhereValue VARCHAR SET @WhereValue = ? EXEC('SELECT ' + @ColumnNames + ' FROM ' + @ViewName + ' WHERE ' + @WhereColumn + ' = ' + @WhereValue)";
}
foreach($_POST['WhereClause'] as $where){
echo $where['ColumnName'];
}
$form_search_parameters = array($column_names, array(&$_POST["ViewName"]), array(&$_POST["WhereClause"]));
}
我正在努力在PHP中返回ColumnName,ColumnValue和Operator Keys,因为我想将它们作为变量传递给参数化查询。非常感谢任何帮助,让我走上正确的轨道。
答案 0 :(得分:0)
您的整个方式是引导您使用GET方法,但您使用POST。
尝试将POST更改为GET,看看是否有帮助,然后回到这里。
在你的js中试试这个:
FormSearchXMLHTTPRequest.open("GET", RootData + "global/search/search.php&" + FormSearchData , false);
FormSearchXMLHTTPRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
FormSearchXMLHTTPRequest.send();
在php中肯定会将所有$_POST
更改为$_GET
在设置var FormSearchData = ... ;
要使用POST,最好将FormSearchData作为对象发送:
var FormSearchData = {
"ColumnNames": ColumnNames,
"ViewName": ViewName,
"WhereClause": WhereClause,
"FormSearchExecuted": 1
};
另外,使用var_dump($_POST)
查看缺少的内容