【问题标题】:How to set the href?如何设置href?
【发布时间】:2015-07-28 05:33:24
【问题描述】:

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

当我单击 index.php 页面上的“SHOW”按钮时,它会显示“mesaj”中的消息保留,但会在 index.php 页面中显示它(我不想要!)。

我想要完成的是,当我单击 index.php 上的“SHOW”按钮时,它会将消息的内容显示到另一个 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);
        });
}

【问题讨论】:

  • “我想在 index.php 中设置 href.”是什么意思?
  • @amar 如果我说清楚的话:D alert(mesaj)

标签: javascript php jquery html href


【解决方案1】:

在您的情况下(显然)没有理由从 PHP 转到 JS。如果您需要在加载后更改 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';
}

请注意,请小心,因为&lt;button&gt; 如果在单击时在表单中使用,则会提交表单。这就是为什么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';
});

【讨论】:

  • Tnx,@Mr.Web!现在href设置为“function.php”但是我如何实现动态编写php文件的需要?如果您可以看到,在我的“functions.php”文件中的“show()”函数中,我会根据我在数据库中输入的内容动态编写它。
  • P.S:我在你的 function.php 中没有看到任何文字......在 show() 函数中没有调用 shown
  • $html = '

    基本列表组

      '; while ($title = mysql_fetch_array($titleSql)) { $html .= '
    • '.$title["title"].'
    • '; } $html .= '
    ';回声 $html;
猜你喜欢
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
相关资源
最近更新 更多