我正在尝试将用户的输入(通过UISearchBar完成)发送到我的PHP文件,以搜索商店名称数据库。但是,我的$_POST
变量$searchWord
似乎是空的。
我的快捷代码:
func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
if(searchBar.text!.isEmpty)
{
return
}
searchBar.resignFirstResponder()
doSearch(searchWord: searchBar.text!, searchbar: searchBar )
}
func doSearch(searchWord: String, searchbar: UISearchBar){
mysearchBar = searchbar
mysearchBar.resignFirstResponder()
let myURL = NSURL(string: "http://localhost:8080/searchStore.php")
var request = URLRequest(url:myURL! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
print("name=\(searchWord)")
let postString = "name=\(searchWord)"
request.httpBody = postString.data(using: String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async() {
if error != nil{
self.displayAlertMessage(userMessage: (error?.localizedDescription)!)
return
}
do{
var _: Error?
//STOPPED HERE AS OF NOW
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
self.results.removeAll(keepingCapacity: false)
self.tableView.reloadData()
if let parseJSON = json{
print("json")
if let stores = parseJSON["stores"] as? [AnyObject]{
print("stores")
for storeOjb in stores{
let name = (storeOjb["name"] as! String)
self.results.append(name)
}
self.tableView.reloadData()
}else if(parseJSON["message"] != nil){
print("message")
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil){
self.displayAlertMessage(userMessage: errorMessage!)
}
}
}
} catch {
print(error)
}
}
}
task.resume()
}
func displayAlertMessage(userMessage: String)
{
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
我的PHP文件
<?php
require("Conn.php");
require("MySQLDao.php");
$returnValue = array();
if(empty($_POST["name"])){
$returnValue["message"]= "Missing required field";
echo json_encode($returnValue);
return;
}
$searchWord =htmlentities($_POST["name"]);
$dao = new MySQLDao(Conn::$dbhost, Conn::$dbuser, Conn::$dbpass, Conn::$dbname);
$dao->openConnection();
$storeNames = $dao->searchStore($name);
$dao->closeConnection();
$returnValue["stores"]=$storeNames;
echo json_encode($returnValue);
?>
<?php
类MySQLDao {
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
function __construct($dbhost, $dbuser, $dbpassword, $dbname) {
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpassword;
$this->dbname = $dbname;
}
public function openConnection() {
$this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if (mysqli_connect_errno())
throw new Exception("Could not establish connection with database");
$this->conn->set_charset("utf8");
}
public function closeConnection() {
if ($this->conn != null)
$this->conn->close();
}
public function searchStore($name){
$returnValue = array();
$sql = "SELECT * FROM stores s WHERE s.name LIKE ? ";
$statement = $this->conn->prepare($sql);
if(!$statement)
throw new Exception($statement->error);
$name = '%' .$name. "%";
$result->bind_param("s", $name);
$result->execute();
$result = $statement->get_result();
while($myrow = $result->fetch_object())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
}
?>
并且Conn.php
包含MySQL连接详细信息。
PostString
显示用户输入正确(我能够通过使用断点来解决)。但是,每当我搜索任何内容时,我都会收到一条警告消息,指出“缺少必填字段”表示我的$_POST
变量$searchWord
为空。
有谁知道如何解决这个问题?