簡體   English   中英

AJAX發布請求和字符串連接

[英]AJAX post request and string concatenation

我正在使用jQuery / AJAX來發布請求。 我正在嘗試從第一個文本框中獲取輸入,並將其與url連接起來,並在第二個文本框中顯示結果。 例如,如果用戶輸入asdf則ajax函數將發布該帖子,結果將顯示為http://www.example.com/sdf/ 我有兩個問題,如前所述,我有一個ajax函數,它正在執行發布,但在html中沒有顯示結果(它確實在firebug控制台中顯示)。 其次,如何將輸入連接到url中。 現場現場

<script>
$(document).ready(function () {
    var timer = null;
    var dataString;

    function submitForm() {
        $.ajax({
            type: "POST",
            url: "/concatenate/index.php",
            data: dataString,
            dataType: "html",
            success: function (data) {
                $("#result").html(data);
            }
        });
        return false
    }
    $("#input").on("keyup", function() {
        clearTimeout(timer);
        timer = setTimeout(submitForm, 40);
        var input = $("#input").val();
       dataString = { input : input }
    })
});
</script>
</head>
<body>

<h1>Enter a word:</h1>

<form action="create_entry.php" method="post">
Input: <input type="text" id="input" name="zipcode"></br>
Concatenated Result: <input type="text" id="result" name="location" value="http//www.example.com/ /" readonly></br>
</form>

我建議您將參數傳遞給submitForm而不是使用全局變量存儲數據。

要進行串聯,可以使用.data()方法存儲輸入的原始值,並始終獲取該原始值,然后向其添加新值。

 <!-- remove extra space and "/" -->
<input type="text" id="result" name="location" value="http//www.example.com/" readonly>

$(document).ready(function () {
    var timer = null;
   /* cache $("#result") and store initial url value*/
    var $result=$("#result");
     $result.data('url',$result.val());

    function submitForm( input ) {
        $.ajax({
            type: "POST",
            url: "/concatenate/index.php",
            data: {input:input},
            dataType: "html",
            success: function (data) {
                 /* new value from stored url and new user input*/
                var url=$result.data('url'),
                 newUrl= url+data;
                /* use val() not html() */
                $result.val(newUrl);
            }
        });
        return false
    }


    $("#input").on("keyup", function() {
        /* no point using "$("#input")" to search DOM again when already have "this"*/
        var input = $(this).val();
        clearTimeout(timer);
        timer = setTimeout(function(){
             submitForm(input) ;
        }, 40);


    })
});

它應該是

success: function (data) { 
    $("#result").val( 'http//www.example.com/'+data+'/'); 
}

責怪這個

success: function (data) {
                $("#result").html(data);
            }

對此

success: function (data) { 
        $("#result").attr('value','http//www.example.com/'+data+'/');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM