gpt4 book ai didi

javascript - XMLHTTPRequest 发送数据

转载 作者:行者123 更新时间:2023-11-30 20:45:43 24 4
gpt4 key购买 nike

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

wordpress\wp-content\themes\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\wp-content\themes\twentyseventeen\assets\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\wp-content\themes\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' );

但它不起作用。

最佳答案

试试这个

添加您的用户名和密码

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));
});

关于javascript - XMLHTTPRequest 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48719700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com