从Body请求中包含payload的表单发起Post请求

Initiate a Post request from a form with paylod in the Body request

本文关键字:请求 表单 Post payload Body 包含      更新时间:2023-09-26

我有以下问题。我有一个web服务,它接受post请求,请求体中有一些json数据,并且还返回json数据。现在我想构建一个用户友好的HTML页面来测试这个服务。我有一个表单来填写数据,当用户单击按钮时,JSON应该从表单数据和post到我的web服务中构建,响应应该显示给用户。我该怎么做呢?

jQuery是你的好朋友,看看ajax部分…有很多函数可以伪造请求并直接从表单中获取数据。http://api.jquery.com/jquery.ajax/

这是一个示例,但它需要MySQL数据库PHP由您的提供商支持。

jQuery

$('#form').on('submit', function(e) {
    e.preventDefault();
    var data = $(this).serialize();
    $.POST('path_to_php_file.php', data, function(response) {
        $('#container').append(response);
    });
}
PHP

<?php
$db = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8', USERNAME, PASSWORD);
//the post variables equal the name attribute on your input element in html: <input name="THIS">
$text = $_POST['text'];
$name = $_POST['name']; 
if(isset($text) && isset($name)) {
    $stmt = $db->prepare("INSERT INTO table_name (text, name) VALUES (?, ?)");
    $stmt->execute(array($text, $name));
    echo "Successfully saved.";
} else echo "There was an error.";
$db = null;

另一个选择,如果你只是想测试你的webservice,是使用postman,一个友好的chrome扩展,用于测试web api。

否则,你甚至不需要jQuery。同步帖子很容易编写:

var button = document.getElementById("submit");
button.onclick = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "yourwebservice.com/your-web-service", false);
    xhr.send("{'json_string':['goes'],['here']}");        
    alert(xhr.response);
}