Front: React Backend: Longguo questions

Asked 2 years ago, Updated 2 years ago, 125 views

We are developing a chatbot using React and Jango. What I want to do now is to send it to the server when the user enters a message at the front desk You have to make a move and return the appropriate answer to the front If you look it up on the Internet, it's just an example of getting json with api, so I don't know what to do.

react django

2022-09-21 10:18

1 Answers

Please take 15 minutes to look at the code below. This is an example where when a user enters something and hits an enter, it says, "Did you just say ~ to me?" below it.

It may seem like a joke, but if you think about it anyway,

When the user enters a message at the front desk, send it to the server, take action, and return the appropriate answer back to the front desk

This will be the web application code.

from django.http import JsonResponse

# No tests. Just look at the face
def mockingbird(request):
    humanTalk = json.loads(request.body)
    Mocking = Did you say 'Now' + humanTalk ['message'] + 'ee'?'
    return JsonResponse({'success':true,'message':mocking})
<!-- Not tested, just look at the development -->
<form id="human">
    <input type="text" name="talk" />
</form>
<div id="mockingbird"></div>

<script>
var human = document.getElementById('human');
var mockingBird = document.getElementById('mockingbird');
human.addEventListener('submit', function (e) {
    e.stopPropagation();
    e.preventDefault();
    var request = new XMLHttpRequest();
    request.open('POST', '/mockingbird', true);
    request.onload = function() {
        if (this.status >= 200 && this.status < 400) {
            mockingBirdSound = JSON.parse(this.response);
            if (mockingBirdSound.success) {
                mockingBird.innerHTML += mockingBirdSound.message + '<br />';
            }
        }
    };
    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    request.send({message: e.target.talk.value});
});
</script>

If you make Python-side scripts more sophisticated and make HTML-side JavaScript into a cool component, you'll get what you want.

And that's it, actually. Even if you look at the examples, it's not just that there's something there, but it's really that.

Try it. It's a one-step path.


2022-09-21 10:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.