繁体   English   中英

如何在不刷新页面的情况下使用POST Ajax更新PHP字符串?

[英]How to update PHP string using POST Ajax without page refresh?

我正在尝试将字符串$user_foreach_limit从1更改为2,将2更改为3 ...(在每个按钮上单击+1以上)。 该字符串是foreach。

当前代码:Ajax有效,但是我必须刷新页面才能看到更改。 没有页面刷新怎么办? 是否有其他选择可以使它工作而无需将整个foreach添加到form-show-more.php吗?

HTML

<form method='POST' id='form_show_more'>
  <input type='submit' value='Show more'/>
</form>
<?php
$user_foreach_limit = 1;
foreach ($modules_for_from as $m_foreach_as) if ($tmp++ < $user_foreach_limit) {
  // foreach content
}
?>

AJAX

$('#form_show_more').submit(function(event){
  event.preventDefault();
  $.ajax({
    url: 'form-show-more.php',
    type: 'POST',
    data: $('#form_show_more').serialize(),
    dataType: 'json'
  });
});

形式出现,more.php

$user_foreach_limit = 2;

这非常简单,您可以直接在原始循环所在的位置执行html,需要包装。 jQuery允许您在需要时直接插入html。

将其创建为视图函数,以在需要的地方重复使用它。 该函数无法按原样工作,您需要注入$tmp或其他所需的东西,但是概念上需要将此作为函数。

/functions/myfunction.php

<?php
function myfunction($user_foreach_limit = 1)
{
    # I would check if the value is a number first
    if(!is_numeric($user_foreach_limit))
        $user_foreach_limit = 1;
    # Do your loop stuffs
    foreach ($modules_for_from as $m_foreach_as) {
        if ($tmp++ < $user_foreach_limit) {
        // foreach content
        }
    }
}

添加几个隐藏字段只是为了使其提供一些请求标识标记。

/original-page.php

<form method='POST' id='form_show_more' action="form_show_more.php">
    <input type="hidden" name="action" value="get_more_mods" />
    <input type="hidden" name="increment" value="2" />
    <input type='submit' value='Show more'/>
</form>
<!-- create a wrapper so you can use it to drop the updated html into -->
<div id="table-list">
<?php
# Add the view function
include_once(__DIR__.'/functions/myfunction.php');
# Run the function right on load for incremental 1, ajax will replace this content
myfunction(1);
?>
</div>

<script>
$('#form_show_more').on('submit', function(event){
    event.preventDefault();
    $.ajax({
        // You can get the destination from the form
        url: $('#form_show_more').attr("action"),
        type: 'POST',
        data: $('#form_show_more').serialize(),
        success: function(response) {
            $('#table-list').html(response);
        }
    });
});
</script>

如果发送了错误的请求,请不要执行任何操作。

/form_show_more.php

<?php
# Stop if action not sent
if(empty($_POST['action']))
    die("Invalid request.");
# Stop if the action is not correct
elseif($_POST['action'] != 'form_show_more')
    die("Invalid action.");
# Add the view function
include_once(__DIR__.'/functions/myfunction.php');
myfunction($_POST['increment']);
exit;
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM