从jQuery返回PHP [英] Back to PHP from jQuery

查看:76
本文介绍了从jQuery返回PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过jQuery回显HTML下拉值:

I want to echo the HTML dropdown value through jQuery:

<select id="single">
  <option>Single</option>
  <option>Single2</option>
</select>

<script>
  function displayVals() {
    var singleValues = $( "#single" ).val();
    $( "p" ).html( "<b>Single:</b> " + singleValues);
  }
  $( "select" ).change( displayVals );
  displayVals();
</script>

并回显PHP中的下拉值:

and echo the dropdown value in PHP:

<?php
    echo $single;
?>


推荐答案

您无法先访问PHP中的选择值提交表单。

You can't access select values in PHP without first submitting the form.

这是一个提交到名为submit.php的文件的示例表单

Here's a sample form which submits to a file called submit.php

<form method="post" action="submit.php">

<select id="my_select" name="my_select">
    <option value="1">One</select>
    <option value="2">Two</select>
    <option value="3">Three</select>
</select>

</form>

submit.php的内容如下所示......

The contents of submit.php would look like this...

<?php
echo $_POST['my_select']; // Will output the value of my_select when the form was submitted
?>

您还可以使用ajax将表单中的数据提交到PHP页面,生成PHP页面一些HTML输出并将其返回到您的jQuery,从那里您可以将生成的HTML插入页面中的元素(div)。

You could also use ajax to submit data from your form to a PHP page, have the PHP page generate some HTML output and return it back to your jQuery, from there you can insert the resulting HTML into an element (div) in your page.

<form id="my_form" method="post" action="submit.php">

<label>Select the number of items you'd like @ £5.00 each</label><br>
<select name="my_select">
    <option value="1">One</select>
    <option value="2">Two</select>
    <option value="3">Three</select>
</select>

</form>

<div id="result"></div>

创建一个PHP页面以接收表单中的数据。

Create a PHP page to receive the data from the form.

$price = 5.00;
$noOfItems = $_POST['my_select'];

$totalCost = $price * $noOfItems;

echo "<p>$noOfItems @ $price will cost you $totalCost"; 

然后使用一些jQuery在后台将表单中的数据提交给PHP,然后将生成的HTML放入#result div。

Then use some jQuery to submit the data from your form to the PHP back in the background, and then put the resulting HTML into the #result div.

<script type="text/javascript">
$(document.ready(function(){

    $("#my_select").change(function(){
        $.post("submit.php", $("#my_form").serialize(), function(response){
            $("#result").html(response);
        });
    });

}))
</script>

这篇关于从jQuery返回PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆