XMLHTTPRequest发送数据

时间:2018-02-10 10:25:52

标签: javascript php json wordpress rest

我想用WordPress在数据库中添加帖子。我试过这段代码。

的wordpress \可湿性粉剂内容\主题\ twentyseventeen \的index.php:

<div class="admin-quick-add">
				<h3>Quick Add post</h3>
				<input type="text" name="title" placeholder="Title">
				<textarea name="content" placeholder="Content"></textarea>
				<button id="quick-add-button">Create Post</button>
			</div>

的wordpress \可湿性粉剂内容\主题\ twentyseventeen \资产\ JS:

quickAddButton = document.querySelector("#quick-add-button");

if (quickAddButton) {
	quickAddButton.addEventListener("click", function() {
		var OurPOSTData = {
			"title": document.querySelector('.admin-quick-add [name="title"]').value,
			"content": document.querySelector('.admin-quick-add [name="content"]').value,
			"status": "publish",
		}
		
		//alert (JSON.stringify(OurPOSTData));
		
		var createPost = new XMLHttpRequest();
		createPost.open('POST', 'http://localhost/wordpress/wp-json/wp/v2/posts');
		createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);
		createPost.setRequestHeader("Content-Type", "application/json; charset=utf-8");
		createPost.send(JSON.stringify(OurPOSTData));
	});
}

的wordpress \可湿性粉剂内容\主题\ twentyseventeen \的functions.php

function twentyseventeen_scripts() {
/* Some code */

// My Script
wp_enqueue_script( 'main_js',  get_theme_file_uri( '/assets/js/main.js' ), NULL, 1.0, true);  /* Some code */ } add_action( 'wp_enqueue_scripts', 'twentyseventeen_scripts' );

但它不起作用。

1 个答案:

答案 0 :(得分:1)

试试这个

添加您的用户名和密码

quickAddButton = document.querySelector("#quick-add-button");

if (quickAddButton) {
quickAddButton.addEventListener("click", function() {
    var OurPOSTData = {
        "title": document.querySelector('.admin-quick-add [name="title"]').value,
        "content": document.querySelector('.admin-quick-add [name="content"]').value,
        "status": "publish",
    }

    //alert (JSON.stringify(OurPOSTData));

    var createPost = new XMLHttpRequest();
    createPost.open('POST', 'http://localhost/wordpress/wp-json/wp/v2/posts');
    createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);
    createPost.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    createPost.setRequestHeader('Authorization', 'Basic ' + window.btoa("username:password"));
    createPost.send(JSON.stringify(OurPOSTData));
});