"ourdogs.php", "About_us" => "aboutus.php", "P-6ren">
gpt4 book ai didi

javascript - 将 PHP 数组传递给 JavaScript?

转载 作者:太空宇宙 更新时间:2023-11-04 15:52:34 25 4
gpt4 key购买 nike

我有一个 PHP 数组,如下所示:

$link_array = [
"Our_dogs" => "ourdogs.php",
"About_us" => "aboutus.php",
"Puppies" => "puppies.php",
"Contact" => "contact.php",
"Login" => "login.php",
"Guestbook" => "guestbook.php"
];

我想将此数组传递给 JavaScript,然后将其打印在我的页面上,但如果我在“我们的狗”页面上,我不希望显示该链接。这可能吗?

我已经尝试过这个:

foreach($link_array as $key=>$value){
if(($key == "Our_dogs") && ($value == "ourdogs.php")){
$_SESSION['Our dogs'] = $value;
break;
}

$responseText['Our_dogs'] = $_SESSION['Our_dogs'];
echo json_encode($responseText);

对于 JS 来说:

var response = JSON.parse(this.responseText);
var li = document.createElement('li');
console.log(response.Our_dogs);
li.innerHTML = '<a href=\"' + response.Our_dogs + '\">OUR DOGS</a>';
byId("nav").appendChild(li);

但我对此很陌生,不知道如何做到这一点。我怎样才能以正确的方式做到这一点,是否可以仅打印其他页面的链接(而不是显示的页面)?

最佳答案

为什么需要 JavaScript?

你可以这样做:

$link_array = [
"Our_dogs" => "ourdogs.php",
"About_us" => "aboutus.php",
"Puppies" => "puppies.php",
"Contact" => "contact.php",
"Login" => "login.php",
"Guestbook" => "guestbook.php"
];

foreach($link_array as $key=>$value){
// note that $_SERVER['PHP_SELF'] returns filename with prepended slash
if( '/' . $value != $_SERVER['PHP_SELF'] ){
echo '<li><a href="' . $value . '">' . $key . '</a></li>';
}
}

您需要在 ul#nav 标记中添加 foreach 循环。

此代码未经测试,我假设您没有调用 ajax 请求。

更新:

$link_array = [
"Our_dogs" => "ourdogs.php",
"About_us" => "aboutus.php",
"Puppies" => "puppies.php",
"Contact" => "contact.php",
"Login" => "login.php",
"Guestbook" => "guestbook.php"
];

echo json_encode($link_array);

Ajax :

$.ajax({
dataType: "json",
...
})
.done(function( response ) {
var currentUrl = window.location.href
var currentUrlLastPart = currentUrl.substr(s.lastIndexOf('/') + 1);
for (var key in response)
if(val != currentUrlLastPart){
var li = document.createElement('li');
li.innerHTML = '<a href="' + response[key] + '">' + key + '</a>';
document.getElementById("nav").appendChild(li);
}
});
});

类似这样的吗?

关于javascript - 将 PHP 数组传递给 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42995936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com