【发布时间】:2015-04-23 15:06:57
【问题描述】:
这是js代码,ajax有两个参数,第一个是url,第二个是一个包含类型数据和onsuccess的对象。 (我没有使用jQuery但是我自己定义的函数,代码在问题的最后) 我只想将“文本”字符串发送到 php,那么这样做有什么问题吗?我也尝试将数据更改为数据:{searchinput:"text"},但仍然无法正常工作。
ajax(
'http://localhost/test.php',
{
type: 'POST',
data: "searchinput=text",
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
这是php代码,很抱歉在粘贴时更改了错误的代码。
$searchinput = $_POST["searchinput"];
@ $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
那么错误是
未定义索引:搜索输入
我已经搜索了一些方法,例如将onsuccess函数更改为setTimeout,并再次执行ajax,但它不起作用,只是再次发送数据但php仍然无法获取数据
这是ajax函数
function ajax(url, options) {
if (!options.type) {
options.type = "post"
};
var xhr = new XMLHttpRequest();
xhr.open(options.type, url, true);
xhr.send(options.data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
options.onsuccess(xhr.responseText, xhr)
} else {
options.onfail(xhr.responseText, xhr);
}
};
}
}
【问题讨论】:
-
最好使用 {searchinput: text}
-
也许我错了,但你的 php 查询应该不像
$query = "select * from text where data like'".$searchcon."%' ";
标签: javascript php ajax