如何设置href?

时间:2015-05-16 09:24:44

标签: javascript php jquery html5 href

我有一个按钮,当按下时必须从外部php文件调用函数并将其加载到新页面中。

当我点击" SHOW"我的index.php页面上的按钮,它显示了" mesaj"中的消息,但是在index.php页面中显示它(我不想要!)。

我想要完成的是当我点击" SHOW"我的index.php上的按钮它显示了消息的内容到另一个php页面,名为 - 例如 - content.php。我想设置href。

的index.php

<input type = "button" class="btn btn-primary" id = "show" onClick = "show()" value = "SHOW"/>

的functions.php

function show()
{

    database();

    $sql = "SELECT title FROM `Articles`";

    $titleSql = mysql_query( $sql ) or die("Could not select articles:");

    $html = '<html><body><div class="container"><h2>Basic List Group</h2><ul class="list-group">';

    while ($title = mysql_fetch_array($titleSql)) {
        $html .= '<li class="list-group-item">'.$title["title"].'</li>';
    }

    $html .= '</ul></div></body></html>';

    echo $html;
    //die(json_encode(array("mesaj" => "Entered data successfully ")));

}

function.js

function show(){
        var n = $('#show').val()
        $.post("functions.php", {show:n}).done(function(mesaj){
            //$(document).html(mesaj);
            document.write(mesaj);
        });
}

1 个答案:

答案 0 :(得分:1)

在你的情况下,没有理由(显然)从PHP转到JS。如果在加载DOM后需要更改DOM,则可以使用JS $.post。你可以这样做:

<a href="function.php" class="btn btn-primary" id="show"/>SHOW</a>

这不需要通过JS。

如果您想使用BUTTON并通过JS进行操作,请执行以下操作:

<input type="button" class="btn btn-primary" id="show" value="SHOW"/>

jQuery的:

$('#show').click(function(e){
    e.preventDefault();
    window.location.href = 'function.php';
});

普通JS:

document.getElementById("show").onclick = function(){
    window.location.href = 'function.php';
}

作为注释,请注意,因为<button>如果在单击时在表单中使用,则会提交表单。这就是e.preventDefault();

的原因

假设您的function.php中有多个功能,您需要拨打一个特定功能,我会这样做:

<强> function.php

if(isset($_GET['fn1'])){
    function functionOne(){
      //do something
     }
}

if(isset($_GET['fn2'])){
    function functionTwo(){
       //do something else
    }
}

并以这种方式称呼它:

<a href="function.php?fn1" class="btn btn-primary" id="show"/>SHOW</a>

$('#show').click(function(e){
    e.preventDefault();
    window.location.href = 'function.php?fn1';
    //window.location.href = 'function.php?fn2';
});
相关问题