使用<a> tag

时间:2017-10-03 09:01:07

标签: javascript php jquery html ajax

I have an a-tag which when clicked, page gets reloaded and certain php code is executed. On successful execution of php code the page is then redirected to same page.

Now, the problem is that the page is jumping to the top which I guess is normal unless you don't use ajax. So, if I can get some assistance with the lines of codes below.

html:

<a href="home.php?key=some_value&val=1" id="ajax_reload">Unfollow</a>

on clicking the above link this php code is executed

php:

if(isset($_GET['key']) && isset($_GET['val'])){
            //some task....
            header('location:home.php'); 
        }

NOTE: all codes are is same page home.php if I can do this without reloading the entire page that would really be helpful.

[Edit] I am really sorry to not have added this in my question. I am using php to show bunch of datas on my page from mysql database. hence all datas have same id and class

4 个答案:

答案 0 :(得分:0)

要将重定向页面向下滚动到初始位置,请在位置标题的末尾添加一个片段(#):

if(isset($_GET['key']) && isset($_GET['val'])){
            //some task....
            header('location:home.php#ajax_reload"'); 
}

答案 1 :(得分:0)

更简单的解决方案是使用标记构建链接,并在HTML中添加标记,例如:

<a href="home.php#LinkThisPartOfThePage?key=some_value&val=1" id="ajax_reload">Unfollow</a>
<div name="LinkThisPartOfThePage">...</div>

现在,您的链接将指向特定的div

答案 2 :(得分:0)

如果要在不重新加载页面的情况下在PHP中执行操作,解决方法是使用ajax。

示例:

Html:

<a href="#" id="ajaxButton">Click !</a>

Javascript:

$("#ajaxButton").on('click', function() {
   var btn = $(this);
   $.ajax({
        url : 'phpscript.php?key=somevalue&val=1',
        type : 'GET',
        dataType : 'json', 
        success : function(dataObject, statut){ 
            // some tasks ...
            console.log(dataObject);
        },

        error : function(result, statut, error){
            console.log(erreur);
        }
    });
});

PHP:

<?php
    if(isset($_GET['key']) && isset($_GET['val'])){
        //some task....
        return json_encode($result);
    }
?>

这样,PHP的返回与javascript一起使用任何重新加载

答案 3 :(得分:0)

尝试通过ajax

执行此操作
<a href="javascript:void(0);" class="ajax_reload" data-key="some_value" data-someval="1">Unfollow</a>
    <script>
    $(function(){
        $('.ajax_reload').on('click',function(){
     $.ajax({
                 url : home.php,
                 type:'POST',
                 data : {key: $(this).data('key'), val:$(this).data('someval')},
                dataType:'json',
                success:function(data)
                {
                    if(data.success==1)
                   location.reload();
                }
            });
    });

});

</script>

在家里.php

if(isset($_POST['key']) && isset($_POST['val'])){
            //some task....
           echo json_encode(array('success'=>1));exit();
       }

它可能包含一些语法错误,如何通过ajax

使用它是基本的想法