简体   繁体   English

ajax简单的js变量到php

[英]ajax simple js variable to php

I've seen many js var to php question asked but none seem to help me as its either to complicated or doesn't fit my requirements. 我已经看到很多js var到php问题,但似乎没有人帮助我,因为它要么复杂,要么不符合我的要求。 I'm looking to transfer three variable in js called title, body and author. 我想在js中传输三个变量,称为title,body和author。 Body being a very long string therefor I cannot place in URL. 身体是一个非常长的字符串因此我不能放在URL中。 I am looking for the simplest Ajax code possible that follows this: js var already defined -> ajax -> php var Here is the code I've got so far: 我正在寻找可能的最简单的Ajax代码:js var已经定义 - > ajax - > php var这是我到目前为止的代码:

<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>

Thank you in advance! 先感谢您!

You can do this way simple 你可以这么简单

<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>

inside, insert.php file 在里面,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);
?>

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

Then use $_POST global variable to get the data you wanted. 然后使用$_POST全局变量来获取所需的数据。

$title = $_POST['title'] ; $title = $_POST['title'] ;
$body = $_POST['body'] ; $body = $_POST['body'] ;
$author = $_POST['author'] ; $author = $_POST['author'] ;

More info on ajax post shorthand here: 关于ajax发布简写的更多信息:
https://api.jquery.com/jquery.post/ https://api.jquery.com/jquery.post/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM