简体   繁体   English

将PHP变量传递给带引号的javascript函数

[英]Passing PHP variable to javascript function with quotes

I need to pass these values to a javascript function in the head. 我需要将这些值传递给头部的javascript函数。 The problem is when pulling from the DB some are more than one word, and using a href it cuts it off at a space when passing using javascript:function(vars), and I can't get onclick to work at all. 问题是,当从数据库中提取多个单词时,使用href时,它会在使用javascript:function(vars)传递时在一个空格处将其切断,而我完全无法通过onclick起作用。 I've tried all sorts of combinations of quotes and brackets around the variables ("",'',/", and {) as well as putting quotes around the ones I know will have more than one word before passing (see below). Here is the PHP: 我已经尝试了将各种引号和括号括起来的各种组合(“”,”,/”和{),并在我知道在传递之前会有多个单词的引号周围加上引号(请参见下文)这是PHP:

<?php
    require('config/dbconfig.php');
    $query = "SELECT * FROM news ORDER BY id DESC LIMIT 4";
    if ($stmt = $mysqli->prepare($query)) {
        /* execute statement */
        $stmt->execute();

        /* bind result variables */
        $stmt->bind_result($idn, $titlen, $categoryn, $descn, $postdaten, $authorn);

        /* fetch values */
        while ($stmt->fetch()) {
            //echo 'id: '. $id .' title: '. $title;
            echo "<table border='0'>";
            $shortDescLengthn = strlen($descn);
            if ($shortDescLengthn > 106) {
                $sDCutn = 106 - $shortDescLengthn;
                $shortDescn = substr($descn, 0, $sDCutn);
            } else {
                $shortDescn = $descn;
            }
                        $titlenQuote = "'". $titlen ."'";
                        $descnQuote = "'". $descn ."'";
                        $authornQuote = "'". $authorn ."'";
            echo "
                <h1>". $titlen ."</h1>
                <tr><td>". $shortDescn ."...</td></tr>
                <tr><td><a href='javascript:return false;' onclick='readMore(". $idn .",". $titlenQuote .",". $categoryn .",
                            ". $descnQuote .",". $postdaten .",". $authornQuote .")'>Read More</a></td></tr>
                <tr><td>Written by: " . $authorn . "</td></tr>
                <tr><td><img src='images/hardcore-games-newsbar-border.png' width='470px' /></td></tr>
            ";
        }
        echo "</table><br />";

        /* close statement */
        $stmt->close();
    }

    /* close connection */
    $mysqli->close();
?>

And the function it's going to in the head: 而它的功能将在头:

<script type="text/javascript">
    function readMore(id,title,cat,desc,post,auth) {
        alert(id +","+ title +","+ cat +","+ desc +","+ post +","+ auth);
        var $dialog = $('<div></div>').html('This dialog will show every time!').dialog({autoOpen: false,title: 'Basic Dialog'});
        $dialog.dialog('open');
        $dialog.title = title;
        $dialog.html(desc);
    }
</script>

This is a page using load() in the main index page. 这是在主索引页面中使用load()的页面。 I've had issues with dialog too, but it's not even hitting that point yet so thats the next step. 我也有对话方面的问题,但是还没有达到这个目标,因此下一步就是了。 In case need to know, all jquery includes are on the main index page. 如果需要知道,所有的jquery都在主索引页面上。 The load() is going into a div on the index page, and this works fine so far. load()即将进入索引页面上的div,到目前为止,它仍然可以正常工作。

You're using the same type of quote for both the attribute value delimiter and the JavaScript string delimiter; 属性值定界符和JavaScript字符串定界符都使用相同类型的引号; don't do that. 不要那样做 Also, json_encode the values instead of just wrapping them in quotes, like so: 另外,对值进行json_encode ,而不是仅将其用引号引起来,如下所示:

echo "
    <h1>". $titlen ."</h1>
    <tr><td>". $shortDescn ."...</td></tr>
    <tr><td><a href='javascript:return false;' onclick='readMore(". $idn .",". json_encode($titlen) .",". json_encode($categoryn) .",
    ". json_encode($descn) .",". json_encode($postdaten) .",". json_encode($authorn) .")'>Read More</a></td></tr>
    <tr><td>Written by: " . $authorn . "</td></tr>
    <tr><td><img src='images/hardcore-games-newsbar-border.png' width='470px' /></td></tr>
";

… and you'll also want to HTML-encode them. …,您还需要对其进行HTML编码。

echo "<h1>$titlen</h1>";
echo "<tr><td>$shortDescn...</td></tr>";
echo '<tr><td><a href="javascript:return false;" onclick="'
    . 'readMore(' . $idn . ',' . htmlspecialchars(json_encode($titlen)) . ','
    . htmlspecialchars(json_encode($categoryn)) . ','
    . htmlspecialchars(json_encode($descn)) . ',' . htmlspecialchars(json_encode($postdaten)) . ','
    . htmlspecialchars(json_encode($authorn)) . ')">Read More</a></td></tr>';
echo "<tr><td>Written by: $authorn</td></tr>";
echo '<tr><td><img src="images/hardcore-games-newsbar-border.png" width="470px" /></td></tr>';

ProTip™: <tr> can't be directly after <h1> . ProTip™: <tr>不能直接在<h1>

You're currently doing something like this: 您当前正在执行以下操作:

echo "<a href='#' onclick='doSomething('" . $someData . "');'>...";

As you noted, this will not work because the quotes conflict. 如您所述,这将无法工作,因为引号冲突。 There's a quick way to fix this, but I think it would be better if you changed it a little bit more. 有一种快速的方法可以解决此问题,但是我认为如果您再对其进行一些更改会更好。

First, start by putting your data in attributes: 首先,首先将数据放入属性中:

echo "<a ... data-title=\"" . htmlspecialchars($title) . "\" ...>...";

Note how I am escaping the title before I put it in there. 请注意在将title放到那里之前,如何转义title You can add more attributes like that, but you should make them all start with data- . 您可以添加更多这样的属性,但应使它们全部以data-开头。

Next, apply a class to it. 接下来,对其应用一个class For example, read-more . 例如, read-more

echo "<a ... class=\"read-more\" data-title=\"" . htmlspecialchars($title) . "\" ...>...";

Now you can bind event listeners to it. 现在,您可以将事件侦听器绑定到它了。 Say all of the items were contained in a div with an id of items . 假设所有项目都包含在具有items iddiv中。 You could then do this in the JavaScript: 然后,您可以在JavaScript中执行此操作:

$("#items").on("click", ".read-more", function(e) {
    var me = $(this);
    var title = me.attr('data-title');
    alert("The title is:\n" + title);
    e.preventDefault();
});

You could then extend that to pop up a dialog or whatever you wanted it to do. 然后,您可以将其扩展为弹出对话框或您想执行的任何操作。


Why this way and not the 'easy' way? 为什么用这种方式而不是“简单”的方式?

This way is a start to separating the content, presentation, and behavior, which is generally considered a good thing. 这种方式是分离内容,表示形式和行为的开始,通常认为这是一件好事。 Before, you had table s for layout and presentation mixed with the content mixed with inline JavaScript for behavior; 以前,您将用于布局和表示的table s与用于行为的内联JavaScript混合在一起; a big soup of stuff. 一汤的东西。

Separating this all out aids maintainability and can often bring better load times if the common things are put into separate files and cached by the browser. 如果将所有常见内容放入单独的文件中并由浏览器缓存,则将所有这些内容分开可以提高可维护性,并且通常可以带来更好的加载时间。 If it's all a big soup, the browser can't cache the pieces separately. 如果这是一大汤,浏览器将无法分别缓存碎片。

<html>
<head>
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
function login(t) {
alert(t);
}
</SCRIPT>
</head>
<body>
<?php
$id=$_GET['id'];
print "<input type='button' name='button' value='button' onClick=login('$id')>";
?>
</body>
</html>

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

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