我正在使用 phonegap 和 jquery mobile 制作一个网络应用程序 (android)。
我正在尝试将 html 表单中的三个字段作为 json 发送到一个 php 页面,该页面将解码 json 字符串/对象(我是 json、ajax、jquery 的新手)并将这三个字段作为 mysql 查询添加到我本地主机上的数据库。
我的 html 页面如下所示:
<script type="text/javascript">
$(document).ready(function(){
$('#btn').bind('click', addvalues);
});
function addvalues(){
$.ajax({
url: "connection.php",
type: "POST",
data: "id=" + $("#id").val()+"&name=" + $("#name").val() + "&Address=" + $("#Address").val(),
datatype:"json",
success: function(status)
{
if(status.success == false)
{
//alert a failure message
}
else {
//alert a success message
}
}
});
}
</script>
</head>
<body>
<div data-role="header">
<h1>My header text</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" placeholder="ID">
</label>
<label for="name">
<input type="text" id="name" placeholder="Name">
</label>
<label for="Address">
<input type="text" id="Address" placeholder="Address">
</label>
<input type="submit" id "btn" value="Add record" data-icon="star" data-theme="e">
</form>
</div>
</body>
问题是:
我如何从发送到我的 php 文件 (connection.php) 的字符串中提取三个字段(ID、名称、地址)? connection.php 由我的本地服务器托管。
我熟悉与数据库建立连接,也熟悉向 mysql 添加查询。我只需要提取三个字段的帮助,因为我是 ajax、jquery 和 json 的新手。
截至目前,这是我在 connection.php 中所做的全部:
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "jqueryex";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
//I do not know how to use the json_decode function here
//And this is how, i suppose, we will add the values to my table 'sample'
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
请在此文件中添加相关代码并帮助我。 我将非常感激。 :)
最佳答案
你想干什么干什么
$(document).ready(function () {
$('#btn').on('click', function () {
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
},
datatype: "json",
success: function (status) {
if (status.success == false) {
//alert a failure message
} else {
//alert a success message
}
}
});
});
});
然后在你的 php 中执行此操作
//set variables from json data
$data = json_decode($_POST); // Or extract(json_decode($_POST) then use $id without having to set it below.
$id = $data['id'];
$name = $data['name'];
$Address = $data['Address'];
//And this is how, i suppose, we will add the values to my table 'sample'
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
请确保在插入之前对这些输入进行清理。
关于用于解析 JSON 并添加到数据库 mysql 的 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11362846/