0

我有一个 JQuery 使用的工作 Ajax,并且正在通过 JSON 响应更改页面上列出的内容。

它与文本完美配合,但是,现在我计划使用相同的代码,但显示视频而不是显示 mpg 的位置。但是,它只是显示来自 youtube 的嵌入代码的文本。

获取 JSON 响应的 Html 页面:

 $(document).ready(function()
    {
            $("#submitbutton").click(function()
            {
                    $.ajax(
                    {
                            url: "https://example.com/jsonServer.php",
                            type: "GET",
                            dataType: "jsonp",
                            jsonp: "callback",
                            data: { carselection: $("#carselection").val()},
                            success: function(data)
                            {
                                    if(data.name == "error")
                                    {
                                            $("#outputcarname").text("There is no such car available"),
                                            $("#price").text(" "),
                                            $("#mpg").text(" ");
                                    }
                                    else
                                    {
                                            $("#outputcarname").text(data.name),
                                            $("#price").text(data.price),
                                            $("#mpg").text(data.mpg);
                                    }
                            },
                            error: function()
                            {
                                    $("#outputcarname").text("There is a problem with the server"),
                                    $("#price").text(" "),
                                    $("#mpg").text(" ");
                            }
                    });
            return false;


 });
});
</script>

JSON服务器:

*请注意,我已将其中一个 mpg 替换为直接来自 youtube 的嵌入代码,并且此嵌入代码再次显示与 mpg 区域中的完全相同。

  <?php

    $cars = array('Maxima' => array('price' => '$32,780', 'mpg' => '24'),
                  'Prius' => array('price' => '$25,565', 'mpg' => '49'),
                  'Element' => array('price' => '$22,075', 'mpg' => '<iframe width="560" height="315" src="http://www.youtube.com/embed/enXTiYWQl-0" frameborder="0" allowfullscreen></iframe>'));

    if(array_key_exists($_GET['carselection'], $cars))
    {
            $carname = $_GET['carselection'];
            $results = array('name' => $carname, 'price' => $cars[$carname]['price'], 'mpg' => $cars[$carname]['mpg']);
    }
    else
    {
            $results = array('name' => 'error');
    }

    $callback = htmlentities($_GET['callback'], ENT_QUOTES);
    print $callback . '(' . json_encode($results) . ')';
    ?>

我希望浏览器会接受标签并明显显示视频,但是我猜 jquery.text 将其保留为真正的文本。也许还有另一个我不知道应该使用的功能?

4

1 回答 1

2

改变这个:

$("#mpg").text(data.mpg);

至:

$("#mpg").html(data.mpg);

.text()将字符串视为文本。

.html()将字符串视为 html

jQuery:文本()与 html()?

于 2012-12-06T04:18:01.607 回答