在foreach循环AJAX [英] AJAX within a foreach loop
问题描述
我不熟悉AJAX和我有困难的时候努力学习是我需要的东西。 我需要写在foreach循环Ajax调用。 如果我只是用PHP呼吁他们将所有消防,即使我不使用onclick事件。 什么即时通讯基本上做的是写出从数据库列表,并添加一个删除按钮,该行。 删除链接被点击时,它会触发一个查询来更新数据库字段的项目。
I am unfamiliar with AJAX and am having a difficult time trying to learn it for what I need. I need to write ajax calls within a foreach loop. if i just use PHP calls they will all fire even if i don't use the onclick event. What im basically doing is writing out a list from the DB and adding a remove button to the row. when the remove link is clicked, it will fire a query to update a field in the DB for item.
我的index.php文件
<?php foreach ($items as $item) : ?>
<tr>
<td><?php echo $item['item_name']; ?></td>
<td><a href="#" onclick="ajax call(arguments)" ></a></td>
</tr>
<?php endforeach; ?>
我的PHP code:(注:我用的词preSS的$ WPDB查询WP数据库查询是否有效没有用户输入,而其上。管理页面,所以不要担心prepare()或其他注射的防御。)
My PHP code: (note: I am using wordpress's $wpdb to query the WP database. query is valid. There is no user input, and its on an admin page so dont worry about prepare() or other injection defenses. )
<?php
$wpdb->query("UPDATE " . $wpdb->prefix."item
SET is_removed =" . $remove_option . "
WHERE item_id =" . $item_id );
?>
($ remove_option前面的index.php页面填充,和$ ITEM_ID来自$ items数组)
($remove_option is populated earlier in the index.php page, and $item_id comes from $items array)
我需要通过2个变量通过Ajax调用,填充$ remove_option和$ ITEM_ID。 火查询,返回到index.php页面。
I need to pass 2 variables through the ajax call, populate $remove_option and $item_id. fire the query, return to index.php page.
我如何使用Ajax来实现这一目标?我完全不熟悉阿贾克斯,我没有使用插件可湿性粉剂,只有PHP脚本。
How do I use ajax to achieve this? I'm completely unfamiliar with ajax, and i am not using a plugin for WP, only php scripts.
推荐答案
HTTP://$c$cx.word press.org / Plugin_API / Action_Reference / wp_ajax_(动作)
add_action('wp_ajax_update_this', 'update_this_func');
add_action('wp_ajax_nopriv_update_this', 'update_this_func');
function update_this_func(){
$remove_option = $_POST['remove_option'];
$item_id = $_POST['item_id'];
global $wpdb;
$wpdb->query("UPDATE " . $wpdb->prefix."item
SET is_removed =" . $remove_option . "
WHERE item_id =" . $item_id );
return json_encode(['status' => 'Updated!']); // return status as json
}
Ajax调用
HTTP://$c$cx.word$p$pss.org/ AJAX_in_Plugins
function onClickingThis(rem_opt,itemid){
$.ajax({
url: ajax_url, // You can get this from admin_url('admin-ajax.php') function
type: 'POST',
data: {action: 'update_this', remove_option: rem_opt, item_id: itemid },
dataType: 'json',
success: function(response){
console.log(response);
}
});
}
这篇关于在foreach循环AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!