从值列表框中更改ajax URL

时间:2015-11-12 16:03:35

标签: jquery ajax listbox

如何更改AJAX网址以使其从select

获取其值
<html>
    <head>
        <title>Tester</title>
        <link href="css/style.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="lib/jquery-1.9.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("#button").click(function() {
                    $("#loading").show();
                    var artikel = $("#text").val();
                    $.ajax({
                        type: "POST",
                        url: "<path>/test1.php", // <-- change url from listbox value test1.php / test2.php / test3.php
                        data: "text=" + artikel,
                        success: function(msg) {
                            $("#result").show();
                            $("#result").html(msg);
                            $("#loading").hide();
                        }
                    });
                });

                $("#reset").click(function() {
                    $("#result").html("");
                });
            });
        </script>
    </head>

    <body>
        <center>
            <form>
                <select id="listbox">
                    <option value="test1.php">Test 1</option>// send value to ajax url
                    <option value="test2.php">Test 2</option>// send value to ajax url
                    <option value="test3.php">Test 3</option>// send value to ajax url</select>
                <br/>
                <br/>
                <textarea placeholder="Write your text here..." class="custom" rows="10" cols="80" name="isi" id="text"></textarea>
                <br/>
                <br/>
                <input type="button" value="Go" class="btn-rewriter btn-rewriter-success" id="button">
                <input type=reset id="reset" class="btn-clear btn-clear-success" value="Clear">
            </form>
            <img src="img/loading.gif" style="display:none" id="loading">
            <br/>
            <br/>
            <div id="result" style="display:none;"></div>
        </center>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

您可以使用select阅读当前选定的val()值,并将其附加到网址字符串:

$("#button").click(function(){
    $("#loading").show();
    $.ajax({
        type: "POST",
        url: "<path>/" + $('#listbox').val(), // < appended here
        data: { 
            text: $("#text").val()
        },
        success: function(msg){
            $("#result").html(msg).show();
            $("#loading").hide();
        }
    });
});

另请注意,我将data属性更改为对象,以便jQuery将根据需要为您编码。