我现在正处于泡菜中...我有这个函数从页面获取2个变量然后在抓取数据后运行sql查询。
function delete(id,date){
confirmdel=confirm('Are you sure?');
if(confirmdel){
var curid = id;
var when = date;
//sql code should go here
}
else{
//don't do anything
return false;
}
}
如何从函数运行SQL查询或将数据发送到php文件?我尝试使用jquery,但它会忽略它,所以如果我可以使用jquery,请解释/给出一个如何使用它的例子。
答案 0 :(得分:4)
JavaScript无法自行处理数据库,它只能告诉浏览器要做什么,并且仅在服务器将页面提交到浏览器后才加载。所以我想你必须使用AJAX。使用jQuery非常简单:
...
$.post('process.php', {id:curid, date : when}, function(data) {
alert(data);
//data contains all output from process.php,
//either in json-format if you jsonencode a results-array
//or just a simple string you echo in the php
return false; //prevent from reloading the page
});
...
您的process.php可能类似于:
<?php
$curid = $_POST['id'];
$when = $_POST['date'];
//run the query
echo jsonencode($results_array);
//or check if query succeeded and echo e.g. 'ok' or 'failed'
?>
你明白了......;)
//编辑:
您应该使用jQuery UI对话框来避免评论中描述的消息。它可能是这样的:
<div id="dialog_box" style="display: none;">
Really delete?
</div>
$('#dialog_box').dialog({
title: 'Really delete this stuff?',
width: 500,
height: 200,
modal: true,
resizable: false,
draggable: false,
buttons: [{
text: 'Yep, delete it!',
click: function(){
//do the post
}
},
{
text: 'Nope, my bad!',
click: function() {
$(this).dialog('close');
}
}]
});
答案 1 :(得分:0)
制作网络服务。 jQuery具有允许您调用Web服务的函数,但您无法使用jQuery构建Web服务。
答案 2 :(得分:0)
AFAIK,您不能通过网页上的JavaScript直接运行SQL查询。即便如此,这也是最糟糕的事情。
实现的最好方法是编写一个服务(REST服务非常合适),它将连接到db,处理数据。然后通过JavaScript处理该服务将是一种更好的方法。
查看JQuery.ajax() API,了解如何向服务器发送Http帖子。
答案 3 :(得分:0)
您应该将数据发送到php文件。
$.post("delete.php", { id: id, date: date }, function(){alert('delete success!');} )
.error(function() { alert("error"); });