我在wordpress中写了一个插件。它有一些.js
文件和.php
文件,我通过在jquery中调用ajax方法从db接收数据。 当我使用wp_enqueue_script
并将它们添加到wordpress时,它工作正常。但我的问题是如何使用wp_ajax
方法,而不是原始的ajax调用。 这里是我的代码:如何在wordpress插件中兼容ajax
:
$(document).ready(function(){
$('#submit').on('click', function(){
var name = $('input[name=name]').val();
var price = $('input[name=price]').val();
var goods = $('input[name=goods]').val();
var date = $('input[name=delivery]').val();
if(name.length > 1 && price.length >1 && goods.length > 1 && date.length >1){
var obj = {
name: name,
price: price,
goods: goods,
date: date
};
var btn=$(this).button('loading');
$.ajax({
url: "service.php",
method: "POST",
data: obj,
dataType:'json',
success: function(e){
$('#alt-div').html('<div id="alert" class="alert alert-info alert-dismissable"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>'+e.Comment+'</div>');
},
error: function(){
alert('error');
}
})
}
});
});
在service.php文件:
$name = $_POST['name'];
$goods = $_POST['goods'];
$date = $_POST['date'];
$price = $_POST['price'];
$tmp = explode('/', $date);
$jy = $tmp[0];
$jm = $tmp[1];
$jd = $tmp[2];
$query = "INSERT INTO products (name, goods, price, date) VALUES ('$name',
'$goods', '$price', '$time')";
results = mysql_query($query);
$inserted_id= mysql_insert_id();
if ($results > 0)
echo json_encode ([
'status'=>1,
'Comment'=>"ok"]);
检查此https://stackoverflow.com/questions/43557755/how-to-call-ajax-in-wordpress – vel