有没有一种方法可以在没有<form>的情况下将JSON发送到php处理器?

时间:2019-07-08 21:16:30

标签: javascript jquery html

我有一页纸的表单https://apply.1hallmark.com,我想在表单开头收集联系信息,而不提交表单。我正在尝试使用javascript。

HTML:

<fieldset>
                    <h2 class="fs-title">Contact Information</h2>
                    <h3 class="fs-subtitle">How can we reach you?</h3>
                    <input id="firstName" type="text" name="first_name_{$Question_DivisionName}" placeholder="First Name" />
                    <input id="lastName" type="text" name="last_name_{$Question_DivisionName}" placeholder="Last Name" />
                    <input id="userEmail" type="email" name="email_address_{$Question_DivisionName}" placeholder="Email" />
                    <input id="userPhone" type="tel" name="phone_number_{$Question_DivisionName}" placeholder="Phone"/>
                    <input id="contactButton" type="button" name="go" class="action-button" value="Go!"/>
                </fieldset>

带有jQuery的Javascript:

// Send Contact Info
    $(function(){
        $("#contactButton").click(function(){
            first_name = $("#firstName").val();
            last_name = $("#lastName").val();
            user_email = $("#userEmail").val();
            user_phone = $("#userPhone").val();
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "https://apply.1hallmark.test/submit-contact.php", true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send(JSON.stringify({
                "first_name": $("#firstName").val(),
                "last_name": $("#lastName").val(),
                "user_email": $("#userEmail").val(),
                "user_phone": $("#userPhone").val()
            }));
        });
    });

所有提交内容当前都已发送到电子邮件地址,但“ POST”:[]为空白。我已经尝试了上面的代码。变量存储在单击按钮时,然后将帖子发送到/submit-contact.php。

3 个答案:

答案 0 :(得分:1)

$_POST不适用于编码为JSON的参数。如果仅以$_POSTapplication/x-www-form-urlencode格式发送参数,PHP只会将其放在multipart/form-data中。

如果您使用jQuery $.ajax函数或快捷方式$.post函数,它将对其正确编码。

$(function(){
    $("#contactButton").click(function(){
        var first_name = $("#firstName").val();
        var last_name = $("#lastName").val();
        var user_email = $("#userEmail").val();
        var user_phone = $("#userPhone").val();
        $.post("https://apply.1hallmark.test/submit-contact.php", {
            "first_name": first_name,
            "last_name": last_name,
            "user_email": user_email,
            "user_phone": user_phone
        });
    });
});

如果要使用fetch(),则可以使用$.param()对POST参数进行编码:

   $(function(){
        $("#contactButton").click(function(){
        var first_name = $("#firstName").val();
        var last_name = $("#lastName").val();
        var user_email = $("#userEmail").val();
        var user_phone = $("#userPhone").val();
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "https://apply.1hallmark.test/submit-contact.php", true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send($.param({
                "first_name": first_name,
                "last_name": last_name,
                "user_email": user_email,
                "user_phone": user_phone
            }));
        });
    });

答案 1 :(得分:0)

是的,可以将JSON发送到基于PHP的后端,而HTML页面中没有<form>元素。这可以使用JavaScript来完成。

看到正在使用JQuery,可以使用内置的$.ajax()方法,而不是使用XMLHttpRequest对象来简化代码。

这些更改可能看起来像这样:

$(function() {
  $("#contactButton").click(function() {

    first_name = $("#firstName").val();
    last_name = $("#lastName").val();
    user_email = $("#userEmail").val();
    user_phone = $("#userPhone").val();

    $.ajax("https://apply.1hallmark.test/submit-contact.php",
    {
      method: 'POST',
      contents: {
        "first_name": first_name,
        "last_name": last_name,
        "user_email": user_email,
        "user_phone": user_phone
      }
    })
    .done(function(data) {
      console.log('Request response:', data)
    })
    .fail(function(err) {
      console.log('Error:', err)
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<label>firstName</label>
<input value="test first_name" id="firstName" />
<br>
<label>lastName</label>
<input value="test last_name" id="lastName" />
<br>
<label>userEmail</label>
<input value="test user_email" id="userEmail" />
<br>
<label>userPhone</label>
<input value="test user_phone" id="userPhone" />
<br>
<button id="contactButton">ContactButton</button>

答案 2 :(得分:-1)

您好,您可以使用Fetch Method向服务器发送请求

示例:

   document.getElementById('contactButton').onclick = function(){
    var url = 'yourURL.php';
    var data = {
                first_name : $("#firstName").val(),
                last_name : $("#lastName").val(),
                user_email : $("#userEmail").val(),
                user_phone : $("#userPhone").val()
    };

    fetch(url, {
      method: 'POST',
      body: JSON.stringify(data), // data can be `string` or {object}!
      headers:{
        'Content-Type': 'application/json'
      }
    }).then(res => res.json())
    .catch(error => console.error('Error:', error))
    .then(response => console.log('Success:', response))

    }

希望有帮助

相关问题