[英]Javascript/jquery .load passing variable
Stuck on a jquery/javascript function that is attempting to .load a set PHP script but passing get variable parameters. 卡在试图加载一个PHP脚本但传递get变量参数的jquery / javascript函数上。 As an aside this is set to happen automatically after 5 seconds. 顺便说一句,这将设置为5秒钟后自动发生。 New to posting here but have read a lot of posts and can't seem to find exactly what I am doing wrong. 此处新发布的帖子,但已经阅读了很多帖子,而且似乎找不到确切的我在做错的事情。
This function works: 此功能有效:
function LoadMyPhpScript()
{
$('#MyDiv').load('hello.php');
}
setTimeout(LoadMyPhpScript,5000);
This function does not work: 此功能不起作用:
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'hello.php';
strURL = strURL + cPhpParamString;
$('#MyDiv2').load(strURL);
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
Here's the hello.php 这是hello.php
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Note: this is just a mock-up, would use regex to validate gets, etc in production. 注意:这只是一个模型,将在生产中使用正则表达式来验证获取等。
RESOLVED 解决
Here is what I ended up with, thank you! 这就是我最后得到的,谢谢!
function LoadMyPhpScript1(cPhpParamString)
{
$('#MyDiv1').load('hello.php'+cPhpParamString);
}
setTimeout(function() { LoadMyPhpScript1('?MyVar1=0&MyVar2=1'); },5000);
When you do this: 执行此操作时:
LoadMyPhpScript2('?MyVar1=0&MyVar2=1')
You are executing the function and passing the result to setTimeout
您正在执行该函数并将结果传递给setTimeout
Try this: 尝试这个:
setTimeout(function() { LoadMyPhpScript2('?MyVar1=0&MyVar2=1'); },5000);
However, sending the url querystring like that is an odd way of doing it. 但是,像这样发送url查询字符串是一种奇怪的方式。 Something like this might be better: 这样的事情可能会更好:
function LoadMyPhpScript2(myVar1, myVar2)
{
var strURL = 'hello.php';
$('#MyDiv2').load(strURL, { myVar1: myVar1, myVar2: myVar2 });
}
setTimeout(function() { LoadMyPhpScript2(0, 1); },5000);
Better try this way: 最好这样尝试:
File help3.html: 文件help3.html:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'help3.php';
strURL = strURL + cPhpParamString;
$.ajax({
url: strURL
}).done(function(data) { // data what is sent back by the php page
$('#MyDiv').html(data); // display data
});
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
</script>
</head>
<body>
<div id="MyDiv">
</div>
</body>
</html>
File help3.php: 文件help3.php:
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Test on my localhost, and both files on the same folder. 在我的本地主机上测试,并将这两个文件放在同一文件夹中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.