猿问

AJAX Post 请求仅适用于 Web 控制台(预览版)

我有一个非常简单的 ajax 请求来“发送”用户在网站上单击的元素的 ID。该脚本仅适用于 Web 控制台(在网络 -> 预览部分)。这发生在每个浏览器中。


这是代码:


AJAX 请求


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>


<script>

    $('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {

        var itemid = event.target.id;   


        $.ajax({

           type: 'post',

           //url: "index.php",

           data: {'itemid' : itemid}, 

           cache : false,

           async : true,

           dataType: 'html',

           success: function(data) {

                      alert('success');     

           },

           failure: function(data) {

                    alert('failure');

           }    

          });

    });

    </script>

PHP函数


    <?php   

  

  if(isset($_POST['itemid'])){

        $itemid = $_POST['itemid'];


        echo "success";

        $itemid = (int)$itemid;

        echo $itemid;

    } else{

    echo "failure";}

  

  ?>


你能帮我解决这个问题吗?


只需添加图像即可让您更好地理解。


心有法竹
浏览 126回答 2
2回答

守着一只汪

这是对你有用的东西。如果它不起作用,那么请分享您的整个代码以及来自 PHP 的响应。// jQuery AJAX call should be something like this$.ajax({&nbsp; &nbsp; url: 'index.php',&nbsp; &nbsp; data: {&nbsp; &nbsp; &nbsp; &nbsp; "itemid": itemid&nbsp; &nbsp; },&nbsp; &nbsp; type: "post",&nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; success: function(json) {&nbsp; &nbsp; &nbsp; &nbsp; if(json.success) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Item ID is " + json.itemid);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Item ID is " + json.itemid);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; error: function(jqXHR, textStatus, errorThrown) {&nbsp; &nbsp; &nbsp; &nbsp; alert("Error :: " + textStatus + " :: " + errorThrown);&nbsp; &nbsp; }});// PHP code can be like thisif(isset($_POST['itemid'])){&nbsp; &nbsp; $itemid = $_POST['itemid'];&nbsp; &nbsp; echo json_encode(['success' => true, 'itemid' => $itemid]);} else {&nbsp; &nbsp; echo json_encode(['success' => false, 'itemid' => 'Not available']);}
随时随地看视频慕课网APP
我要回答