doukezi4576 2015-06-25 11:21
浏览 39
已采纳

使用Ajax,Jquery和PHP Echo打印选择选项

I have looked throughout Stackoverflow and seen numerous examples of this but none give the answer how to echo. I am have a select dropdown that is on a page called testing.php:

<form id="projects" action="project-add.php" method="POST">
<select name="territory" id="territory">
<option value="Australia">Australia</option>
<option value="Argentina">Argentina</option>
</select>

// A fair few more form fields here

<input type="submit" value="Submit Project">
</form>

I now need whatever is selected here to be available to echo as a php variable later down the form without the need to press a button.

I have the following script in the :

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$('#territory').change(function(e) {
    e.preventDefault();
    var selectedOption = $(this).find('option:selected');
    $('#territory option').removeAttr('selected');
    $(selectedOption).attr('selected','selected');
    var selectedOptionValue = $(selectedOption).val();
    var selectedOptionText = $(selectedOption).text();


    $.ajax({
    url: 'testing.php', 
    type: 'POST', 
    data: {data : selectedOptionText},
    dataType: 'text',
    success: function(data){ }
 });
 });//]]>


 });

</script>

I would then like to print:

<? echo $_POST['data']; ?>

But this isn't working. Your help would be appreciated.

Thanks in advance

  • 写回答

5条回答 默认 最新

  • duancong6937 2015-06-25 11:40
    关注

    DEMO

    1. You need to be able to trigger the change

    <select name="territory" id="territory">
      <option value="">Please select</option>
      <option value="Australia">Australia</option>
      <option value="Argentina">Argentina</option>
    </select>
    

    2. then call the php with the selected option

    $(function() { // on page load
      $('#territory').on("change",function(e) {
        $("#someOutputContainerID").empty(); // clear the container
        var selectedOptionValue = $(this).val();
        if (selectedOptionValue) { // in case they select "Please select"
          $.ajax({
            url: 'testing.php', 
            type: 'POST', 
            data: {data : selectedOptionValue },
            dataType: 'text',
            success: function(data){
              $("#someOutputContainerID").html(data);
            }
          });
        }
      });
    });
    

    The selected value is now available in the testing.php as $_POST["data"] and anything echoed in testing.php will show in the container

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料