【js】ajax发送接收数据代码-AI科大讯飞/豆包/通义灵码等提供

编程开发

ajax.jpg
想玩网页斗地主,于是想自己弄1个。不过这玩意不使用websocket的话,就得用ajax和服务器交换数据。websocket不会,就先简单的研究下ajax吧。等吧ajax摸透,先弄个简单的聊天室,然后再搞个网页字符版斗地主。。。
对js不是很懂,还好可以用ai来辅助编程。。。

            function handleJsonRequest(method, url, data, expectResponse = true) {
            return fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: method === 'POST' || method === 'PUT' ? JSON.stringify(data) : undefined
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP Error: ${response.status}`);
                }
                
                if (expectResponse) {
                    // 如果需要返回服务器响应的JSON数据
                    return response.json();
                } else {
                    // 如果不需要返回数据,则直接返回true表示成功
                    return true;
                }
            })
            .catch(error => {
                console.error('Error processing request:', error);
                // 抛出错误以便外部捕获并处理
                throw error;
            });
}

调用的时候这样就可以了:

        //发送聊天信息给服务器并获得返回数据
        handleJsonRequest('POST', 'chat.php', {
            action: 'sendchat',
            chatroomname,
            username,
            chatcontent
        },true)
        .then(response => {
            // chatid = response.chatid;                    
            // document.getElementById('chatrecord').value += `${username}: ${chatcontent}\n`;
        })
        .catch(error => {
            console.error('Error sending chat:', error);
        });
   


标签: javascript, js, ajax, fetch, json, promise

+0 +7
新评论

请填写评论信息

暂无评论