使用jquery ajax -json错误将json发送到php服务器

我的网页上的表单有问题。 我试图使用ajax和json将表单值发送到php服务器,但我无法正确生成json对象。

我的JS代码

function sendJsonOpenPopout () { $('.submitBtn').click(function(e){ e.preventDefault(); var subject = $('.subject').val(); var email = $('.email').val(); var message = $('.message').val(); var dataObject = { subject: subject, email: email, message: message } $.ajax({ type: 'POST', url: '../../kontakt.php', contentType: "application/json", dataType: 'json', data: dataObject, success: function(data){ alert('Items added'); }, error: function(){ console.log('You have fail'); } //success: function(){ //var createdDiv = '

Wiadomość została wysłana pomyślnie.\brDziękuję za kontakt.

'; //$('body').append(createdDiv); //} }); });

我的PHP代码

  

我知道有类似的问题已经问过,但答案对我没有帮助。

谢谢你的帮助。

我能够获取json对象并在php端解析它。 某些变量可能命名为不同,部分原因是其中一些变量是预先编写的代码。 以下是我采取的步骤。

文件夹结构

 js/script.js php/get_data.php index.html 

Index.html一个基本表格。

 

script.js提交,收集数据并将其设置为对象并通过ajax发送到php。

 $(function() { // process the form $('#feedbackform').submit(function(event) { // get the form data - obj that will POSTED to get_data.php var formData = { 'email' : $('#email').val(), 'subject' : $('#subject').val(), 'message' : $('#message').val() }; // process the forum $.ajax({ type : 'POST', // define the type of HTTP verb we want to use (POST for our form) url : 'php/get_data.php', // the url where we want to POST data : formData, // our data object dataType : 'json', // what type of data do we expect back from the server encode : true }) // using the done promise callback .done(function(data) { // log data to the console so we can see if ( ! data.success) { console.log(data); } else { console.log(data); } }); // stop the form from submitting the normal way and refreshing the page event.preventDefault(); }); }); 

get_data.php从script.js接收数据,进行一些validation,然后发送和发送电子邮件。

 '; //subject of the email $subject = $info_data[1]; $result = str_replace(' ', ' ', $info_data[2]); $result = nl2br($result); $result = wordwrap($result, 70, "\r\n"); //body of the email. $message = ""; $message .= "

" . $result . "

"; $message .= "
"; $message .= ""; $headers = "From: Email, Some " . "\r\n" . 'Reply-To: '. $info_data[0] . "\r\n" ."X-Mailer: PHP/" . phpversion(); $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=UTF-8"; //sent mail: check to see if it was sent. if(mail($to, $subject, $message, $headers)){ $data["went"] = "went"; $data['message'] = 'Success!'; }else{ $data["went"] = "didn't go"; $data['message'] = 'Sorry!'; } // echo the log echo json_encode($data); } ?>

如果您有任何疑问,请告诉我。 我很乐意回答。