我在这里屁股踢自己,因为我不能为我的生活弄清楚...这应该是一个快速而肮脏的项目,但是,我决定我想尝试新的东西,并且我对jQuery中的AJAX方法几乎没有经验...我花了5天的时间试图学习和理解如何正确实现AJAX调用,但是知道有用......我学到了一些基本的东西,但不是什么我需要执行下面的代码。
同样,我想知道如何使用jQuery将此标准请求转换为AJAX ...
这是我的表格& PHP
HTML:
<form action="categories.php?action=newCategory" method="post">
<input name="category" type="text" />
<input name="submit" type="submit" value="Add Categories"/>
</form>
PHP:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['category'])) {
if ($_GET['action'] == 'newCategory') {
$categories = $_POST['category'];
$query = "SELECT * FROM categories WHERE category ='$categories' ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)) {
echo '<script>alert("The Following Catergories Already Exist: ' . $categories . '")</script>';
} else {
// Simply cleans any spaces
$clean = str_replace(' ', '', $categories);
// Makes it possible to add multiple categories delimited by a comma
$array = explode(",", $clean);
foreach ($array as &$newCategory) {
mysql_query("INSERT INTO categories (category) VALUES ('$newCategory')");
}
echo "<script>alert('The following Categories have been added successfully: " . $categories . "')</script>";
}
}
} else {
echo "<script>alert('Please Enter at Least One Category.')</script>";
}
}
?>
答案 0 :(得分:1)
这是在后台进行调用而不提交表单但仍然发送/检索结果的正确语法。
$(function(){
$('form').submit(function(e){
e.preventDefault(); // stop default form submission
$.ajax({
url: 'categories.php',
data: 'action=newCategory',
success: function(data){
//here we have the results returned from the PHP file as 'data'
//you can update your form, append the object, do whatever you want with it
//example:
alert(data);
}
});
});
});
此外:
我不会这样做 - &gt;
echo "<script>alert('Please Enter at Least One Category.')</script>";
只需echo 'Please Enter at Least One Category.';
如果您需要创建错误系统,可以执行以下操作:
echo "Error 1001: <!> Please enter at least One Category!';
然后在Ajax回调中'成功',我们可以在<!>
中拆分返回的对象。示例如下:
success: function(data){
if($(data+':contains("<!>")'){
var errMsg = $(data).split('<!>');
alert(errMsg[0]+' : '+errMsg[1]);
//above would output - Error 1001 : Please enter at least One Category!;
}
}