4

I am currently creating a website and am having trouble using AJAX to post my data. I have a button and when clicked the following code is processed...

var name = document.getElementById('name').innerHTML;
var text = document.getElementById('text').innerHTML; 

$.ajax({  
    type: "POST",  
    url: "php/post.php",  
    data: { postName: name, postText: text},  
    success: function() {  
        $('#paragraph').html("worked");    
    }  
});  

This definitely opens the post.php page but it is not passing through the desired data. Am I doing something wrong?

Thanks in advance

4

4 回答 4

7

What do the variables name and text contain? Rather than doing

var name = document.getElementById('name').innerHTML;
var text = document.getElementById('text').innerHTML; 

You can do:

var name = $("#name").val(); 
var text = $("#text").val();

You may need to pass the datatype object too:

$.ajax({  
type: "POST",  
url: "php/post.php",  
data: { postName: name, postText: text}, 
dataType: "json",
success: function() {  
    $('#paragraph').html("worked");    
}  
});  
于 2012-05-24T18:34:04.390 回答
4
var name = $('#name').text();
var text = $('#text').text(); 

$.ajax({  
  type: "POST",  
  url: "php/post.php",  
  data: { postName: name, postText: text}, 
  dataType: 'json',
  success: function() {  
    $('#paragraph').html("worked");    
  }  
});  
于 2012-05-24T18:35:56.023 回答
0

I guess you are not preventing the default button click behaviour. Probably you should use the preventDefault function on the button click to stop processing the default form posting. Also make sure you have the content present inside your form elements with the Id name and text

$(function(){  

    $("#yourButtonId").click(function(e){
    {
      e.preventDefault();
      var name = $('#name').html();
      var text = $('#text').html();

      if(name!="") 
      {    
         $.ajax({  
           type: "POST",  
           url: "php/post.php",  
           data: { postName: name, postText: text},  
           success: function() {  
              $('#paragraph').html("worked");    
           }   
         });  
       }
       else
       {
         alert("Why should i do ajax when content is empty!");
       }
    }); 

});
于 2012-05-24T18:35:23.560 回答
0
var name = document.getElementById('name').value,
    text = document.getElementById('text').value, 
    postData = JSON.stringify({ postName: name, postText: text});
$.ajax({  
    type: "POST",  
    url: "php/post.php",  
    data: postData,
    success: function() {  
        $('#paragraph').html("worked");    
    }  
});

You will need to include a reference to json2.js for this to work in older browsers. You can download it here : https://github.com/douglascrockford/JSON-js

于 2012-05-24T18:38:42.753 回答