我现在有一个来自我的 PHP 脚本的有效 JSON 格式的文件。
下一步是使用 JavaScript 脚本检索这些数据以进行排序、过滤和显示。
我有一个可用的 Ajax 脚本,可以测试是否可以拉回数据,但我需要针对个人进行个性化设置。
在 PHP 中,我有一个名为 MID(成员(member) ID)的 Session 变量。
我正在尝试使用 PHP 来构建具有唯一 URL 且 MID 作为变量的 JavaScript。
除了用外部 PHP 脚本中的 MID 变量替换 JavaScript 文本中的 midValue 变量外,以下所有内容似乎都有效。
到目前为止的代码看起来像这样......
// This is a PHP file
// Setup PHP Output Buffering to change the MID value
session_start();
$MID = $_SESSION['MID'];
function callback($buffer)
{
return (str_replace("midValue", $MID, $buffer));
}
ob_start("callback");
/*
Some bits I can't show as I haven't figured out the correct Stackoverflow tags (!) ...
- Add the usual HTML tags such as `HTML, HEAD, TITLE, BODY, SCRIPT` etc
- Include a DIV with an ID of **json**, this will be replaced by the JSON output it
self.
- Enclose the params variable with the `CDATA` tags to maintain the ampersand.
*/
params = "url=server.com/content.php?action=json&MID=" + midValue
request = new ajaxRequest()
request.open("POST", "getcontent.php", true)
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if(this.status == 200)
{
if(this.responseText != null)
{
document.getElementById('json').innerHTML = this.responseText
}
else alert("Ajax Error: No data recieved")
}
else alert("Ajax Error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
/*
Add the closing `SCRIPT, BODY and HTML` tags here.
*/
ob_end_flush();
getcontent.php 文件看起来像这样......
if(isset($_POST['url'])) {
echo file_get_contents("http://" . SanitizeString($_POST['url']));
}
function SanitizeString($var) {
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
最佳答案
我认为像这样更简单的东西应该适合你。
<?php
session_start();
$MID = $_SESSION['MID'];
?>
params = "url=server.com/content.php?action=json&MID=<?php echo $MID ?>"
request = new ajaxRequest()
request.open("POST", "getcontent.php", true)
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
... // rest of javascript
<?php include 'footer.php'; // include footer code here ?>
使用这种方法,您只是在 PHP 之外输出 javascript 和 html,因此您不需要在标签中使用它。然后,您可以只回显变量或在需要时包含页眉和页脚。
关于来自 PHP 的 JavaScript(使用 Ajax)和输出缓冲,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8246956/