我有 index.php:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.on').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val}
});
});
$('.off').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val}
});
});
});
</script>
<body>
<img class="bulb" src="bulb.png" alt="...">
<button class="on" value="http://pageon.org">On</button>
<button class="off" value="http://pageoff.org">Off</button>
</body>
我将按钮的值发送到 try.php。根据点击的按钮,我在 try.php 文件中得到一个变量,对于 ON 按钮 - 1 ,对于 OFF 按钮 - 0(变量$curl_response
)。是否可以根据从 try.php 页面收到的变量动态更改 index.php 文件中的 img?例如,如果接收到的变量是1,src = "bulb.png",如果是0,那么src = "bulb2.png"?
尝试.php:
<?php
$name = $_POST['myVar'];
$service_url = $name;
$curl = curl_init($service_url);
// Ustaw opcje połączenia
curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
//curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
curl_close($curl);
?>
编辑:
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val}
success: function(result){
switch(result){
case "0":
$(".bulb").attr("src", "bulb.png");
break;
case "1":
$(".bulb").attr("src", "bulb2.png");
break;
}
}
});
});
});
</script>
看看success
你传递给的选项$.ajax
。如果 https 请求状态为 200,您可以在此处提供要运行的回调函数。类似
$.ajax({
/** your other stuff, and... */
success : function(data) {
if (data == 1) {
$('button.on').attr({src : "bulb.png"})
}
// and so on
}
});
有关更多信息,请参阅http://api.jquery.com/jQuery.ajax/。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句