如何使用JQuery/AJAX调用php函数
以下内容位于我的html文件头部的脚本标记中:如何使用JQuery/AJAX调用php函数,ajax,html,jquery,Ajax,Html,Jquery,以下内容位于我的html文件头部的脚本标记中: $(document).ready(function(){ $("#Submit").click(function(){ var name = $("#name").val(); $.ajax({ url : "function.php",
$(document).ready(function(){
$("#Submit").click(function(){
var name = $("#name").val();
$.ajax({
url : "function.php",
type : "POST",
data : {"firstname":name},
success : function(n){
//more code here }
});
});
}
这是HTML表单:
<div class="myForm">
<input name="name" id="name" value="name" onfocus="if (this.value == 'Name') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Name';}" type="text" />
<input type="button" value="Submit" id="Submit">
</div>
这是我的PHP,保存在一个名为function.PHP的文件中:
<?php
$con=mysqli_connect( "test", "", "", "test");
// Check connection
$name = $_POST['firstname'];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO customers (name) VALUES (" + $name + ")");
mysqli_close($con);
?>
该函数需要一段时间才能调用,并且我的数据库中没有保存任何内容。我不熟悉JQuery/Ajax。我的调试选项是什么?可能出现什么问题?请尝试此代码。我已经编辑了您的代码并添加了PDO,这是连接数据库的新方法。。 这样更安全,并且自动转义数据 您的php中有许多语法错误。与php中的字符串附加运算符类似,它是
而不是+
<?php
$name = $_POST['firstname'];
try {
// Prepare our connection string and execute it
$con = new PDO("mysql:host=".HOST.";dbname=".DBNAME, USER, PASS);
} catch(PDOException $e) {
// Connection error jumps here
echo $e->getMessage();
}
// Define our query here
$query = $con->prepare("INSERT INTO customers (name) VALUES (:name)");
// Define our query data here. the name here maps to the :name in the query.
$data = array("name" => $name);
try {
// Try to execute our query
$query->execute($data);
} catch(PDOException $e) {
// Insert error jumps here
echo $e->getMessage();
}
?>
只要在代码中提到的地方输入主机、数据库名、用户和密码,就可以了
要调试php代码,请在firefox和html页面上安装Firebug
,右键单击页面并选择Inspect element with Firebug
,打开Firebug。打开Net
面板,您可以看到请求正在进行。查看响应,您将在php页面上看到任何可能的错误
祝你好运 您正在发布名为
firstname
的变量,并检索名为name
的变量。他们应该匹配。您还可以尝试使用mysqli\u查询(…)或die(mysqli\u error())
查看任何mysql错误。数据格式:data:{firstname:name},
@showdev我现在已经进行了此编辑。函数的执行速度要快得多,但我的表中仍然没有数据:(你又拼写错了!@showdev是对的。此外,别忘了mysqli\u real\u escape\u string($con,$name)