2016-11-24 59 views
1

我見過很多js var to php的問題,但沒有人能幫助我,因爲它要麼複雜或不符合我的要求。 我期待在js中調用稱爲標題,正文和作者的三個變量。身體是一個非常長的字符串,因此我不能在URL中放置。 我正在尋找最簡單的Ajax代碼可能是如下這樣: JS變種已定義 - > AJAX - > PHP變種 這是到目前爲止,我已經得到了代碼:ajax簡單的js變量到php

<script> 
var title; 
var body; 
var author; 
function post(){ 
    title = document.getElementById("title").value; 
    body = document.getElementById("body").value; 
    author = document.getElementById("author").value; 
} 
    //Insert ajax code here 
<?php 


$title; 
$body; 
$author; 
$post = "INSERT INTO post (title, body, author) VALUES ($title,$body,$author)"; 
$sql = mysqli_query($conn,$post); 
?> 
</script> 

預先感謝您!

+0

__「//此處插入Ajax代碼」 __創造這麼多的問題,它不應該有.... – Rayon

+0

在這裏添加您的Ajax代碼,你試過了什麼? – Elby

+0

Ajax代碼不能在PHP下。 –

回答

3

你可以做這樣簡單的

<script> 
var title = document.getElementById("title").value; 
var body = document.getElementById("body").value; 
var author = document.getElementById("author").value; 

$.ajax({ 
    type: 'POST', 
    url: 'insert.php',     
    data: {title:title,body:body,author:author}, 
success: function(data) { 

} 
}) 
</script> 

內,insert.php文件

<?php 
$title = $_POST['title']; 
$body = $_POST['body']; 
$author = $_POST['author']; 
$post = "INSERT INTO post (title, body, author) VALUES ($title,$body,$author)"; 
$sql = mysqli_query($conn,$post); 
?> 
+0

感謝這個我的JS函數post()工作,但Ajax似乎不工作,因爲它不更新數據庫。我試圖將JS警報放入insert.php中進行測試,但它並未激活。謝謝你的幫助! –

+0

你不可以在insert.php裏面放一個JS alert,你可以打印$ _POST的值,它會得到你的值。你的ajax –

+0

對不起,它沒有答案,你不能在JS插入.php,JS你的AJAX不工作,我認爲你的腳本沒有添加,請添加它「「,你可以打印$ _POST值,它會得到你的值。我希望它有幫助。 –

0

$.post('url', {title: title, body: body, author: author})

然後使用$_POST全局變量來得到你想要的數據。

$title = $_POST['title'];
$body = $_POST['body'];
$author = $_POST['author'];在阿賈克斯後速記這裏

更多信息:
https://api.jquery.com/jquery.post/