简体   繁体   English

通过jQuery-AJAX load()函数将PHP变量作为变量传递给JavaScript

[英]Passing PHP variables to JavaScript as variable through jQuery-AJAX load() function

I have 2 files, main.html and search.php . 我有2个文件, main.htmlsearch.php

Within the main.html page, there is this piece of code : main.html页面中,有这段代码:

$("#results").load("search.php",queryString,function(response,status,xhr){
... some code here
})

Within the search.php page, there is this piece of code : search.php页面中,有这段代码:

$image_id=mysql_insert_id() // getting the last ID of the last query - works perfectly

What I want to do is to echo this variable to the main.html file and store it within a JS variable called im_id that I can call through the main.html page. 我想要做的是将此变量回显到main.html文件并将其存储在一个名为im_id的JS变量中,我可以通过main.html页面调用它。

I tried to do this 我试着这样做

echo "<script type=\"text/javascript\">$im_id=".mysql_insert_id()."</script>";

but it doesn't work at all. 但它根本不起作用。

I found a workaround which is to store the content within a textbox like this 我找到了一种解决方法,即将内容存储在像这样的文本框中

echo "<script type=\"text/javascript\">$(\"#textbox\").val(".$image_id.")</script>";

and then in the JScript, use 然后在JScript中使用

$im_id=$("#textbox").val();

and many other methods using an "intermediary" but isn't there a straight way to set the variables directly ? 以及使用“中介”的许多其他方法但是没有直接设置变量的方法吗?

Any help would be appreciated. 任何帮助,将不胜感激。

Its not working because you output $im_id=1 , you should output var im_id = 1; 由于输出$im_id=1 ,它不起作用,你应该输出var im_id = 1; instead. 代替。

In your PHP: 在你的PHP中:

echo "<script type=\"text/javascript\">var im_id = ".mysql_insert_id().";</script>";

If it still doesnt work look at the generated code, not the PHP source. 如果它仍然无法工作,请查看生成的代码,而不是PHP源代码。 Just go to view source in your browser, and use a debugger to find out whats wrong. 只需在浏览器中查看源代码,然后使用调试器找出错误的信息。

The reason it's not working is that php replaces variables inside double quotes with the value of your variable. 它不起作用的原因是php用双引号内的变量替换变量的值。 This makes for easy templating. 这样可以轻松模板化。 For more information see the variable parsing section of the php docs. 有关更多信息,请参阅php文档的变量解析部分

 <?php $juice = "apple"; echo "He drank some $juice juice.".PHP_EOL; // Invalid. "s" is a valid character for a variable name, but the variable is $juice. echo "He drank some juice made of $juices."; ?> 

The above example will output: 上面的例子将输出:

 He drank some apple juice. He drank some juice made of . 

Either replace the double quotes with single if you want to have a variable name in javascript that starts with a $: 如果您想在javascript中以$开头的变量名称,请将双引号替换为单引号:

echo '<script type=\"text/javascript\">$im_id='.mysql_insert_id().'</script>';

or, don't use a $ in your variable name: 或者,不要在变量名中使用$:

echo "<script type=\"text/javascript\">im_id=".mysql_insert_id()."</script>";

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

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