duanqian3953
2014-07-04 06:56
浏览 44

Javascript没有替换PHP脚本中的InnerHTML

I have been working on a Garry's Mod loading screen recently and basically I was attempting to 'simplify' the map name by replacing it with a phrase. However, it appears PHP isn't printing the array value.

$map = $_GET["map"];
$map_list = array (
    "gm_construct" => "Construct",
    "gm_flatgrass" => "Flatgrass"
);
if (in_array($map, $map_list) == true)
{
    if ($map == $map_list[1])
    {
        print("<script>document.getElementById('map_name').innerHTML = '" . print($map_list['gm_construct']) . "'</script>");
    }
    else if ($map == $map_list[2])
    {
        print("<script>document.getElementById('map_name').innerHTML = '" . print($map_list['gm_flatgrass']) . "'</script>");
    }
}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanchui1251 2014-07-04 07:08
    已采纳

    A couple issues with how you're accessing the associative array $map_list. Use the following:

    <?php
    $map = "Flatgrass"; // $_GET["map"];
    $map_list = array (
        "gm_construct" => "Construct",
        "gm_flatgrass" => "Flatgrass"
    );
    $key = array_search($map, $map_list);
    if ($key !== false) {
        print("<script>document.getElementById('map_name').innerHTML = '" . $map_list[$key] . "'</script>");
    }
    

    If the $_GET value has a key in the $map_list, just use it directly to print the script.

    Don't call print() inside a concatenated string (it outputs directly to standard out, doesn't return a string). And, this reduces your code, by just having one if statement print out the script using the value passed in directly.

    And, in your original code, you can't index $map_list using integers, as you have only used string keys making it an associative array.

    已采纳该答案
    打赏 评论
  • dongshanxun6479 2014-07-04 07:09

    You should try below code :-

    $map = $_GET["map"];
    $map_list = array (
        "gm_construct" => "Construct",
        "gm_flatgrass" => "Flatgrass"
    );
    if (in_array($map, $map_list) == true)
    {
        if ($map == $map_list["gm_construct"])
        {
            print("<script>document.getElementById('map_name').innerHTML = '" . print($map_list['gm_construct']) . "'</script>");
        }
        else if ($map == $map_list["gm_flatgrass"])
        {
            print("<script>document.getElementById('map_name').innerHTML = '" . print($map_list['gm_flatgrass']) . "'</script>");
        }
    }
    
    打赏 评论
  • donglv5269 2014-07-04 07:58

    You should change

    print("<script>document.getElementById('map_name').innerHTML = '" . print($map_list['gm_construct']) . "'</script>");
    

    to

    print("<script>document.getElementById('map_name').innerHTML = '{$map_list['gm_construct']}'</script>");
    

    or you can use

    echo '<script>document.getElementById("map_name").innerHTML = "', $map_list['gm_construct'] ,  '"</script>';
    

    is better.

    打赏 评论

相关推荐 更多相似问题