P粉0381618732023-09-03 13:09:00
When sending data as JSON
, the jQuery method .ajax()
requires passing in an object-unique argument in the object's data
property. Your jQuery.serialize()
function creates the parameter string for the URL. This won't work here. You should use jQuery.serializeArray()
:
function errMsg(code, msg) { const eCode = '<b>E-NS: ' + code + ' </b> </br>' + msg; const eMsg = '<span class="err" style="color: red;">' + eCode + '</span>'; $('.notify').html(eMsg); } $(document).ready(function() { $("#form-2").hide(); $('#next-1').click(function(e) { e.preventDefault(); // console.log("this will be sent to the server:",$('#form-1').serializeArray()); $.ajax({ url: 'https://jsonplaceholder.typicode.com/posts', // '../data.php', method: 'POST', data: $('#form-1').serializeArray(), dataType: 'JSON', success:function(response){ // console.log("this came back from the server:",response); if(response){ $('#form-1').hide(); $('#form-2').show(); errMsg(response.id, JSON.stringify(response)) } else { console.log(response.status); console.log('Response = ' + response.code + response.error); errMsg(response.code, response.error); } } }) }) })
.notify {border: 1px solid grey}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="form-1"> First form ... <br> <input type="text" name="title" value="my very own title"><br> <input type="text" name="size" value="XL"><br> <input type="number" name="quantity" value="3"><br> <button id="next-1" type="button">OK</button> </form> <form id="form-2"> Second form ... <br> <input type="text" name="title" value="some other product title"><br> <input type="text" name="size" value="M"><br> <input type="number" name="quantity" value="5"><br> <button id="next-2" type="button">OK</button> </form> <div class="notify">This is the place for messages ...</div>
You should also check what the server will send back. For my dummy JSON API, the .status
property is not sent back. So there is no point in testing it.
P粉8721820232023-09-03 09:36:17
I hide my toast div ($('.notify')
) until there is text in the div. However, I neglected to add a function that displays this (shown below) and did not call it after updating the toast in the AJAX success 更新 AJAX
function using
errorCheck() Code>
function errorCheck() { if ($('.notify').text().trim().length == 0) { $('.notify').hide(); } else { var time = setTimeout(function() { $('.notify').fadeOut('200'); }, 5000); $('.notify') .show() .mouseout(function () { time; }) .mouseover(function () { clearTimeout(time); }) .click(function() { $('.notify').fadeOut('100'); }); } }