PHP和JQuery:值未更新 - php

几个问题:

1)我试图每次按下按钮时更新一个新的随机值。单击该按钮时,将只生成一个值...但不是随机的。因此,我不确定是否在单击时再次调用该函数,因为不会生成新值。

2)当使用诸如$ .get()之类的服务器调用时,我可以在与jquery相同的文件中包含php代码,并在同一文件中将其作为函数调用吗?

原因是,我不想继续创建新的PHP脚本文件,而宁愿将代码与调用jquery放在同一文件中。

含义...

代替$.get("../scripts/NameGenerator2.php",

我这样做:$.get("a php function within this same file",

jQuery的:

<?php 
   if ($imgid == 1) {
?>
<button onclick="generate()">Generate</button>

<button id="generateButton">Generate</button>

<script type="text/javascript">
    $(document).ready(function() {
        $("#generateButton").click(function(e) {
            //alert("called");
           $.get("../scripts/NameGenerator2.php", 
                function(returned_data) {
                    $("#generated").html(returned_data);
                }
            ).error(function(jqXHR, status, error) {
                console.log("error in $.get")
            });
        });
    });
</script>       
<?php } ?>
<br /><span id="generated"></span><br />

PHP:

<?php 
$adj = array("Happy", "Great", "Mandarin", "New", "Golden", "Ming's");
$noun = array("Dragon", "Sea", "Wok", "Fortune", "Rice", "Empire");
$place = array("Garden", "China", "Village", "Palace", "Kitchen", "Mountain");


$x = rand(0, count($adj)-1);
$y = rand(0, count($noun)-1);
$z = rand(0, count($place)-1);

echo '<p>' . $adj[$x] . " " . $noun[$y] . " " . $place[$z] . '</p>';

?>

有什么想法吗?谢谢!

更新:我似乎得到的唯一错误是“ myJquery.js”文件中的“预期对象”,该文件不是我正在使用的文件,并且似乎未连接。

当我将文档添加到函数中时,按钮onclick()调用似乎中断了。

参考方案

您无法获得PHP函数,但可以加载页面并获得特定的div-

$('#generated').load('../scripts/NameGenerator2.php #pagePart');

例如,您用适当的ID来回显PHP,例如-

echo '<p id="pagePart">' . $adj[$x] . " " . $noun[$x] . " " . $place[$x] . '</p>';

不使用任何内联JavaScript,这就是您的jQuery代码的样子-

<button id="generate">Generate</button>

$(document).ready(function() {
    $('#generate').click(function(e){
        e.preventDefault();
        $('#generated').load('../scripts/NameGenerator2.php #pagePart');
    });
});

根据您的更新,您需要将所有jQuery函数移至文档就绪函数中。

PHP-复选框组 - php

我有一个需要发布的表单复选框组。<input type="checkbox" value="true" checked name="chk0[]"> <input type="checkbox" value="false" name=…

PHP-MySQL结果转换为JSON - php

我试图了解如何将MySQL结果转换为JSON格式,以便以后可以在Javascript中使用此JSON来构建HTML表。但是我的代码只是产生大量的空值,我还不明白为什么。$result = mysqli_query($con, "SELECT * FROM Customers"); $test = json_encode($result);…

PHP Count数组元素 - php

嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…

PHP:从函数返回值并直接回显它? - php

这可能是一个愚蠢的问题,但是……的PHPfunction get_info() { $something = "test"; return $something; } html<div class="test"><?php echo get_info(); ?></div> 有没有办…

PHP:将数据从二维数组复制到一维数组的最快方法 - php

我有一个巨大的二维PHP数组,带有500万行。$t = [ [ "id" => 1, "name" => "foo" ], [ "id" => 2, "name" => "bar" ] ]; 现在,我必须将此数组的I…