SVG代码直接呈现在HTML (<div id="svg">svg-code-here</div>
)。
当用户单击<select name="svg-changer">
的值时,需要替换 SVG 代码。
JS脚本和PHP代码的剥离示例:
$('#svg-changer').on('change', function () {
$.ajax({
type: "post",
cache: false,
url: "/update",
data: {"k": 'svg', "v": this.value},
success: function(resp) {
$("#svg").html(resp);
}
});
});
SVG 代码正在使用 PHP ( /update
检索):
<?php
exit(json_encode('resp' => file_get_contents('path/to/image.svg')));
响应在控制台内可见,但我无法替换当前的 HTML。
使用非 SVG 代码时,#svg
内容将被替换,没有任何问题。
SVG代码应该为jQuery编码吗?
谢谢!
您的 PHP 代码返回一个 JSON 对象,并且您在 ajax 调用中没有以这种方式使用响应。你可以只使用
exit(file_get_contents('path/to/image.svg'));
或者在jQuery调用中dataType
设置为json
并使用resp.resp
,但这没有多大意义,对吧?它会导致类似这样的东西:
$.ajax({
type: "post",
cache: false,
url: "/update",
dataType: "json",
data: {"k": 'svg', "v": this.value},
success: function(response) { // You can name it wherever you want, but...
$("#svg").html(response.resp); // You have to access .resp attribute, set in PHP
}
});
希望对您有所帮助。