我在同一页面中有多个按钮,如50或更多,可以向Ajax wordpress方式提交单个值。它们看起来像这样:
case SCE_DD_COMMENT:
if (scCTX.ch('\n') || scCTX.ch('\r')) {
scCTX.SetState(SCE_DD_DEFAULT);
}
break;
每个按钮应在某些数据库表的行上更新。
它应该使用Ajax调用<input id="1-57977357564a7" class="button-primary" type="submit" value="Done"/>
<input id="2-57977357564a7" class="button-primary" type="submit" value="Done"/>
<input id="3-57977357564a9" class="button-primary" type="submit" value="Done"/>
// And so on, more buttons
update_completed_todos()
我需要传递add_action('wp_ajax_update_completed_todos', 'update_completed_todos');
add_action( 'wp_ajax_nopriv_update_completed_todos', 'update_completed_todos' );
function update_completed_todos() {
global $wpdb;
$table_name = $wpdb->prefix . 'todos';
$id = '';// Need to pass the id here some how
$result = $wpdb->get_results("SELECT id FROM " . $table_name . " WHERE id = '" .$id."'");
if (count ($result) > 0) {
$wpdb->update(
$table_name,
array(
'complete' => '10',
),
array( 'id' => $id )
);
}
}
一些如何使用此功能。
我应该在Ajax中写什么来传递id
?
我如何让每个按钮都针对这个Ajax?
由于Ajax可能无法传递id
而不是值,我应该怎么做才能将任何值传递给Ajax?
Ajax应该是这样的:
id
答案 0 :(得分:1)
尝试:
<强> HTML:强>
<input id="1-57977357564a7" class="button-primary" type="submit" value="Done" onclick="ajax($(this));return false;"/>
<input id="2-57977357564a7" class="button-primary" type="submit" value="Done" onclick="ajax($(this));return false;"/>
<input id="3-57977357564a9" class="button-primary" type="submit" value="Done" onclick="ajax($(this));return false;"/>
<强>使用Javascript:强>
function ajax($this) {
var id = $this.attr("id");
$.ajax({
method: "POST",
url: "your address",
dataType: "your response type",
data: {
id: id
},
success: function (response) {
console.log(response);
}
});
}
<强> PHP:强>
if (isset($_POST["id"])) {
var_dump($_POST["id"]);
exit;
}
当然,您必须将dataType和url更改为您的数据。
wordpress方式
<强>使用Javascript:强>
function ajax($this) {//If you got error "Function ajax is not defined" declare this before document ready
var id = $this.attr("id");
$.ajax({
method: "POST",
url: "<?php echo esc_js( admin_url( 'admin-ajax.php' ) ) ?>",
dataType: "text",
data: {
action: "update_completed_todos",// call the php function
id: id // store id
},
success: function (response) {
console.log(response);
}
});
}
<强> PHP:强>
add_action('wp_ajax_update_completed_todos', 'update_completed_todos');
add_action( 'wp_ajax_nopriv_update_completed_todos', 'update_completed_todos' );
function update_completed_todos() {
$id = $_POST['id'];// store id from ajax
//do something with this id
}