HTML TAG <a> pass variable both with href and onclick

时间:2015-12-04 00:56:21

标签: javascript php jquery href

I want when someone clicks this link to go first on myfunction that I have in JS and after that follow the href function that exists in <a> tag. The problem is that it follows first the href and I can't pass the variable I want from the js function.

here is my code:

PHP

echo '<a href="category.php?id=' . $_SESSION['id'] . '" onclick="myFunction();">
        <div class="icon-lock">
            <img  src="/test/images/lock.png" alt="Locked Button" width="35" height="35" border="0">
        </div>';
echo '</a>';

JS

<script>
function myFunction() {
$.ajax({
        type: "POST",
        data: {id: "1"},
        url: "category.php"
        });
 }
</script>

I am very confused on how href and myfunction will work in order to print

$id=$_POST['id'];
echo $id;

in php after the page has been reloaded...
Any thoughts?

3 个答案:

答案 0 :(得分:2)

你只需在你的功能上传递这个

你的php代码看起来像这样

 echo '<a href="category.php?id=' . $_SESSION['id'] . '" onclick="myFunction(this);">/*pass this keyword to function */
            <div class="icon-lock">
                <img  src="/test/images/lock.png" alt="Locked Button" width="35" height="35" border="0">
            </div>';
    echo '</a>';

function myFunction(str) {
   $.ajax({
        type: "POST",
        url: str.getAttribute("href")
   }).done(function() {
        // What ever following the link does
            window.location.href=str.getAttribute("href")

   });
}

答案 1 :(得分:1)

您可以将'id'作为参数传递给函数,并在ajax成功后使用javascript更改窗口位置。

<强> HTML

<div class="icon-lock">
    <img onclick="myFunction(<?=$_SESSION['id']?>)" src="/test/images/lock.png" alt="Locked Button" width="35" height="35" border="0">
</div>

<强>的Javascript

function myFunction(id) {
    $.ajax({
        type: "POST",
        data: {id: "1"},
        url: "category.php",
        success: function() {
            window.location.assign("category.php?id="+id);
        }
    });
}

答案 2 :(得分:0)

阻止采用事件对象的myfunction方法中的默认操作。然后在成功回调你的ajax请求时,做你想做的事。

<a href="category.php?id=' . $_SESSION['id'] . '" onclick="myFunction(e);">

function myFunction(e) {
   e.preventDefault();
   $.ajax({
        type: "POST",
        data: {id: "1"},
        url: "category.php"
   }).done(function() {
        // What ever following the link does
   });
}