在同一页面上发布帖子而不刷新

时间:2013-11-04 14:31:00

标签: javascript php ajax

如何在不刷新页面的情况下在同一页面上提交表单。我知道可以使用ajax,但我在ajax我的本机编程语言PHP中并不完美。

HTML

<input type="submit" class="topopup1" value="Preview" onclick="capture();" >
<form method="POST" enctype="multipart/form-data"  id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
</form>

的Javascript

function capture() {
$('.showcase').html2canvas({
    onrendered: function (canvas) {
        //Set hidden field's value to image data (base-64 string)
        $('#img_val').val(canvas.toDataURL("image/png"));
        //Submit the form manually
        document.getElementById("myForm").submit();}
     });
  }

PHP

<?php


  //Show the image
  if(isset($_POST['img_val'])){
  echo '<img src="'.$_POST['img_val'].'" />';


  //Get the base-64 string from data
  $filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
  //Decode the string
  $unencodedData=base64_decode($filteredData);

  //Save the image
  file_put_contents('img.png', $unencodedData);
   }
   ?>

3 个答案:

答案 0 :(得分:2)

使用$.post

// When submitting form below is run
$( "#myForm" ).submit(function( e ) {
    // prevent form from sending like normal
    e.preventDefault();
    // Send post with ajax, with the postdata of the html form, whatever your page returns you can catch with .done(function(data));
    $.post( "", $( "#myForm" ).serialize() ).done(function( data ) {
        console.log( "return data: " + data );
    });
}

答案 1 :(得分:2)

你发现它回答了。在我的情况下,我的php响应是image.Now我使用ajax函数.submit提交表单,并将target设置为结果show.and now now not not not需要在同一页面上执行表单操作所以我已经在save.php上更改了操作。

  $("#myForm").ajaxForm
  ({
  target: '#preview'
  })
  .submit();

HTML

<input type="submit"   value="Preview" onclick="capture();" >
 <form method="POST" action="save.php" enctype="multipart/form-data"  id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
 </form>

答案 2 :(得分:1)

(使用jQuery AJAX并不难!这仅用于演示,而不是代码的解决方案:

jQuery / JavaScript

var myId = "this_is_my_id";

var myAjax = $.ajax({
  url: "script.php", //The url to your .php script
  type: "POST", //Method av sending data (POST / GET)
  data: {id : myid}, //variables to send (if GET it looks like this  script.php?id=this_is_my_id ) 
  dataType: "json" //The expected datatype of the answer
});

myAjax.done(function(the_data) {
  //
  // Place magic code that transform the json data (the_data = javascript object) you got from the script
  //
  $("#mydiv").html( your_magic_code );
});

myAjax.fail(function(jqXHR, message) {
  alert( "Failed: " + message );
});

PHP(script.php):

$id = $_POST['id'];

//MAGIC PHP CODE

echo json_encode( MAGIC_CODE_TO_RETURN ); //I.e converting an array to json