http://jquery.malsup.com/form/
で、ここのajaxSubmitを使って、Form記述は普通にしたまま、Formの動きをAjax化しようとしたわけです。
サンプルを見るとこんな感じに書いてあります。
http://jquery.malsup.com/form/#json
http://jquery.malsup.com/form/#ajaxSubmit
Form markup:
<form id="jsonForm" action="json-echo.php" method="post"> Message: <input type="text" name="message" value="Hello JSON" /> <input type="submit" value="Echo as JSON" /> </form>JavaScript:
// prepare the form when the DOM is ready $(document).ready(function() { var options = { target: '#output2', // target element(s) to be updated with server response beforeSubmit: showRequest, // pre-submit callback success: showResponse // post-submit callback // other available options: //url: url // override for form's 'action' attribute //type: type // 'get' or 'post', override for form's 'method' attribute //dataType: null // 'xml', 'script', or 'json' (expected server response type) //clearForm: true // clear all form fields after successful submit //resetForm: true // reset the form after successful submit // $.ajax options can be used here too, for example: //timeout: 3000 }; // bind to the form's submit event $('#myForm2').submit(function() { // inside event callbacks 'this' is the DOM element so we first // wrap it in a jQuery object and then invoke ajaxSubmit $(this).ajaxSubmit(options); // !!! Important !!! // always return false to prevent standard browser submit and page navigation return false; }); });
で、json-echo.phpの中身はこうなっていると。
Server code in json-echo.php:
この通りやると確かに動くわけです。
しかし、ちょっと違和感があります。
json-echo.phpの記述を見る限り、これはおそらく(PHPのデフォルト設定であれば)text/htmlとして返されるはずです。
サンプルページのJSONも、HTTPヘッダを拾ってみると、text/htmlで返されています。 しかし、JSONを返しているわけですから、ここはちゃんとapplication/jsonで返そうよ、と思って とすると、エラーになるのです。(ブラウザによって反応が変わりますが)
で、AJAX側をこのように変えるとエラーにならずに動作します。
Form markup:
<form id="jsonForm" action="#" method="post"> Message: <input type="text" name="message" value="Hello JSON" /> <input type="submit" value="Echo as JSON" /> </form>JavaScript:
// prepare the form when the DOM is ready $(document).ready(function() { // bind form using ajaxForm $('#jsonForm').ajaxForm({ // dataType identifies the expected content type of the server response dataType: 'json', ,url: 'json-echo.php' // success identifies the function to invoke when the server response // has been received success: processJson }); });
やったことと言えば、Form内のactionをそのままajaxオプションurlに移動しただけですが、 どうも、FormのactionにURLが書いてあるかどうかによって挙動が変わってるみたいですね。