使用$ .ajax的第一个脚本,它不起作用

时间:2022-04-05 12:57:17

This would be my very first attempt with jQuery and Ajax (and Jacascript in general), so don't shoot me if it's rubbish!

这将是我第一次使用jQuery和Ajax(以及一般的Jacascript),所以如果它是垃圾,请不要开枪!

What I want to achieve is: having a page product.php where a product is displayed with a nice img and a description. At the bottom putting one <select> menù: when an <option> is clicked, a jQuery code load the code into tester.php passing to it the value of the clicked option. The .php script will analyze the value and, based on its value, it will send a query to extract the relative price and img. Now, before doing this, I wrote a really simple code (following the official documentation and some answers here) that should pass a variable $return back to the HTML page but I guess the callback it doesn't work and I don't have enough experience in jQuery yet to find the problem and a relative solution.

我想要实现的是:拥有一个页面product.php,其中一个产品显示有一个很好的img和一个描述。在底部放置一个

Can anyone more pro explain me why this doesn't work? Thanks!

任何人都可以向我解释为什么这不起作用?谢谢!

ajaxpost.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#menuSelect").on("click", function(){
        var str = $("#menuSelect").val();
        $.ajax({
            type: "POST",
            url: "tester.php",
            data: { value: str },
            success: function(data){
                console.log(data);
            }
        })
    })
});
</script>
</head>

<body>
<div id="txt" >
</div>

<select id="menuSelect">
  <option value="0"></option>
  <option value="1">OPT1</option>
  <option value="2">OPT2</option>
</select>

tester.php

<?php
    $value = $_POST["value"];
    function provaAJAX($value) {
        switch ($value) {
          case "0":
              $return = "First option selected";
              break;
          case "1":
              $return = "Second option selected";
              break;
          case "2":
              $return = "Third option selected";
              break;
        }
        return $return;
    }

    $return = provaAJAX($value);

2 个解决方案

#1


3  

You should print the variable to be passed back to the JS :

你应该打印要传递回JS的变量:

echo $return;

Hope this helps.

希望这可以帮助。

#2


0  

To pass back to JS you should print the variable try this: echo $return;

要传回JS,你应该打印变量试试这个:echo $ return;

#1


3  

You should print the variable to be passed back to the JS :

你应该打印要传递回JS的变量:

echo $return;

Hope this helps.

希望这可以帮助。

#2


0  

To pass back to JS you should print the variable try this: echo $return;

要传回JS,你应该打印变量试试这个:echo $ return;