我是ajax的新手。从 wook 的博客学习基础知识。
我使用下面的代码使用 ajax 插入到我的数据库中。
但是该代码除了“稍等一下”之外不打印任何内容。
JsFiddle链接 Ajax 代码如下:-
/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject() {
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
function insertReply() {
if (http.readyState == 4) {
var response = http.responseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('insert_response').innerHTML = 'User added:' + response;
}
}
/* -------------------------- */
/* INSERT */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('insert_response').innerHTML = "Just a second...";
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var username = encodeURI(document.getElementById('Username').value);
var name = encodeURI(document.getElementById('Name').value);
var password = encodeURI(document.getElementById('Password').value);
document.getElementById('insert_response').innerHTML = 'h ' + username + ' ' + name;
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'insert.php?name=' + name + '&username=' + username + '&password=' + password);
http.onreadystatechange = insertReply;
http.send(null);
}
插入db的php代码是::--
if(isset($_GET['name']) && isset($_GET['username'])&& isset($_GET['password'])){
$name= $_GET['name'];
$username= $_GET['username'];
$password= $_GET['password'];
$sql = "INSERT INTO `vidyasims`.`user_accounts` (`UserID`, `UserName`, `Name`, `Password`) VALUES (NULL, '. $username. ','. $name. ', '. $password. ');";
$insertSite= mysql_query($sql) or die(mysql_error());
//If is set URL variables and insert is ok, show the site name -->
echo $username;
} else {
echo 'Error! Please fill all fileds!';
欢迎支持。提前致谢。
注意 - 上面的代码没有向 db 添加新用户!