JavaScript / Ajax - перейти к URL с содержанием формы - PullRequest
0 голосов
/ 05 декабря 2018

Я пытаюсь заставить пользователя вставить customer_id и затем получить URL-адрес для перехода на эту страницу.

On: http://localhost:8080/viewCustomer.html, Я хочу, чтобы пользователь ввел customer_id, а затем яхочу, чтобы URL перешел на http://localhost:8080/customers/{customer_id}.

Я попытался найти решения здесь, и они не работают.

Полученный URL-адрес получился "http://localhost:8080/viewCustomer.html?customer_id=1"

Вот мой код:

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script>
//            $("#submit").submit(function (event) {
//                $customer_id = $_POST["customer_id"];
//                var newURL = 'http://localhost:8080/customers/' + $customer_id;
//                xhttp.open("GET", newURL, true);
//                xhttp.send();
//            }
//            );

        function changeFormAction() {
            window.location.href = "http://localhost:8080/" + document.getElementById("customer_id");  
        }

    </script>
</head>
<body>
    <h1>Bank Management - View Customer</h1>
    <h3>Please complete of the following:</h3>
    <form onsubmit="changeFormAction()">

        Customer ID:<br>
        <input type="text" name="customer_id" id="customer_id">
        <br>
        <button type="submit" onclick="">Submit</button>
    </form>
</body>
</html>

1 Ответ

0 голосов
/ 05 декабря 2018

Вы включили две древние версии jQuery.Вы должны включить jQuery только один раз и в идеале использовать актуальную версию.

После того, как вы это сделаете, ваш код должен работать следующим образом - вам нужно присвоить своей форме идентификатор, обработайте «submit» в форме (кнопки не имеют события submit), остановите поведение обратной передачи по умолчанию и используйте $ .ajax () jQuery для простой отправки запроса ajax.

<head>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
     <script>
       $(function() {
         $("#customerForm").submit(function(event) {
             event.preventDefault();
             $.ajax({
               type: "GET",
               url: "http://localhost:8080/customers/" + $("#customer_id").val(),
             }).done(function(response) {
               console.log(response);
             }).fail(jqXHR, textStatus) {
               alert( "Request failed: " + textStatus );
             });
         });
      });
    </script>
</head>
<body>
    <h1>Bank Management - View Customer</h1>
    <h3>Please complete the following:</h3>
    <form id="customerForm">
        Customer ID:<br>
        <input type="text" name="customer_id" id="customer_id">
        <br>
        <button type="submit">Submit</button>
    </form>
</body>

Вот несколько ссылок на соответствующую документацию:

http://learn.jquery.com/using-jquery-core/document-ready/

https://api.jquery.com/submit/

https://api.jquery.com/event.preventdefault/

https://api.jquery.com/jquery.ajax/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...